-
Notifications
You must be signed in to change notification settings - Fork 8
/
server.c
73 lines (60 loc) · 1.52 KB
/
server.c
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
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define SAMPLE_SERVER_CONN 10
int main(int argc, char **argv)
{
int ret;
int sock;
int conn;
int set_reuse = 1;
struct sockaddr_in remote;
socklen_t remote_len;
if (argc != 3) {
fprintf(stderr, "%s [ip] [port]\n", argv[0]);
return -1;
}
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0) {
perror("failed to socket\n");
return -1;
}
ret = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &set_reuse, sizeof(set_reuse));
if (ret < 0) {
perror("failed to setsockopt\n");
close(sock);
return -1;
}
remote.sin_family = AF_INET;
remote.sin_addr.s_addr = inet_addr(argv[1]);
remote.sin_port = htons(atoi(argv[2]));
ret = bind(sock, (struct sockaddr *)&remote, sizeof(remote));
if (ret < 0) {
perror("failed to bind\n");
close(sock);
return -1;
}
ret = listen(sock, SAMPLE_SERVER_CONN);
if (ret < 0) {
perror("failed to listen\n");
close(sock);
return -1;
}
remote_len = sizeof(struct sockaddr_in);
conn = accept(sock, (struct sockaddr *)&remote, &remote_len);
if (conn < 0) {
perror("failed to accept\n");
close(sock);
return -1;
}
printf("new client %d\n", conn);
close(conn);
return 0;
}