-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.cc
More file actions
106 lines (85 loc) · 2.09 KB
/
server.cc
File metadata and controls
106 lines (85 loc) · 2.09 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
// server.cc -- a simple socket server - serves only a single client
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define MAXDATASIZE 1000
#define BACKLOG 10
int main(int argc, char *argv[]) {
int sockfd;
int new_fd;
struct addrinfo hints, *servinfo;
struct sockaddr_storage their_addr;
socklen_t sin_size;
char s[INET_ADDRSTRLEN];
int rv;
char buf[MAXDATASIZE];
int numbytes;
if (argc != 2){
printf("usage: server portnum\n");
exit(1);
}
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
if ((rv = getaddrinfo(NULL, argv[1], &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
exit(1);
}
if ((sockfd = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol)) == -1) {
perror("server: socket");
exit(1);
}
if (bind(sockfd, servinfo->ai_addr, servinfo->ai_addrlen) == -1){
close(sockfd);
perror("server: bind");
exit(1);
}
freeaddrinfo(servinfo);
if (listen(sockfd, BACKLOG) == -1) {
perror("listen");
exit(1);
}
printf("server: waiting for connections on port %s...\n", argv[1]);
sin_size = sizeof their_addr;
// blocking
new_fd = accept(sockfd, (struct sockaddr*)&their_addr, &sin_size);
if (new_fd == -1) {
perror("accept");
exit(1);
}
inet_ntop(their_addr.ss_family, &((struct sockaddr_in*)&their_addr)->sin_addr, s, sizeof s);
printf("server: got connection form %s\n", s);
close(sockfd);
while (1) {
// error
if ((numbytes = recv(new_fd, buf, sizeof buf, 0)) == -1) {
perror("recv");
close(new_fd);
exit(0);
}
// client stop (return value 0)
if (numbytes == 0) {
close(new_fd);
break;
}
// print message
buf[numbytes] = '\0';
printf("server: received '%s'\n", buf);
// send message to client
if (send(new_fd, buf, strlen(buf), 0) == -1) {
perror("send");
close(new_fd);
exit(0);
}
}
close(new_fd);
return 0;
}