-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.c
More file actions
62 lines (48 loc) · 1.24 KB
/
Copy pathserver.c
File metadata and controls
62 lines (48 loc) · 1.24 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
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#define SERVER_PORT 5000
#define BUFLEN 300
int main(int argc, char *argv[]){
int sock, clientsock;
struct sockaddr_in cliAddr,srvAddr;
/*create socket*/
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0) {
perror("fail to create a socket");
exit(EXIT_FAILURE);
}
srvAddr.sin_family = AF_INET;
srvAddr.sin_addr.s_addr = htonl(INADDR_ANY);
srvAddr.sin_port = htons(SERVER_PORT);
//bind server address
if(bind(sock, (struct sockaddr *)&srvAddr, sizeof(srvAddr)) < 0 ) {
perror("fail to address");
exit(EXIT_FAILURE);
}
listen(sock, 50);
//start to read data from clients
while(1) {
printf("%s: start to wait connetions from client on TCP port %u\n", argv[0] , SERVER_PORT);
int clilen;
clilen = sizeof(cliAddr);
clientsock = accept( sock, (struct sockaddr *)&cliAddr, &clilen);
if(clientsock < 0) {
perror("fail to address");
exit(EXIT_FAILURE);
}
//read data
int n;
char buf[BUFLEN];
while( (n = recv(clientsock, buf, BUFLEN, 0)) > 0 ) {
write(STDOUT_FILENO, buf, n);
}
if(n < 0) perror("recv error\n");
}
close(sock);
}