-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.c
More file actions
86 lines (66 loc) · 1.87 KB
/
Copy pathserver.c
File metadata and controls
86 lines (66 loc) · 1.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
int PORT = 9003;
int main(int argc, char *argv[]) {
if(argc > 1) {
PORT = atoi(argv[1]);
}
else {
printf("Using default port because argument [PORT] was not given\n");
}
int s, n, ns;
struct sockaddr_in myAddr;
bzero(&myAddr, sizeof(myAddr));
myAddr.sin_family = AF_INET;
myAddr.sin_addr.s_addr = INADDR_ANY;
myAddr.sin_port = htons(PORT);
struct sockaddr_in cliAddr;
socklen_t len = sizeof(cliAddr);
char buf[1025];
s = socket(PF_INET, SOCK_STREAM, 0);
if(s == -1) {
printf("Error while creating a socket...\n");
exit(1);
}
n = bind(s, (struct sockaddr *) &myAddr, sizeof(myAddr));
if(n == -1) {
printf("Error while binding...\n");
exit(1);
}
n = listen(s, 5);
if(n == -1) {
printf("Error listening...\n");
exit(1);
}
while(1) {
printf("Waiting for client connection...\n");
ns = accept(s, (struct sockaddr *) &cliAddr, &len);
if(ns == -1) {
printf("Error while accepting client connection...\n");
exit(1);
}
printf("Client connected...\n");
// Receive length of payload
int length = 0;
while((n = recv(ns, &length, sizeof(length), 0))) {
if(n == -1) {
printf("Error while receiving length...\n");
close(ns);
}
n = recv(ns, buf, length, 0);
if(n == -1) {
printf("Error while receiving payload...\n");
exit(1);
}
buf[length] = '\0';
printf("%d\t%s\n", length, buf);
}
close(ns);
}
return 0;
}