-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathepoll.c
More file actions
executable file
·106 lines (82 loc) · 2.19 KB
/
epoll.c
File metadata and controls
executable file
·106 lines (82 loc) · 2.19 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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <netdb.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/epoll.h>
#include <errno.h>
#include <pthread.h>
int make_socket_non_blocking(int sfd)
{
int flags, s;
if((flags = fcntl(sfd, F_GETFL, 0)) == -1) {
perror("make_socket_non_blocking (getfl): fcntl");
return -1;
}
flags |= O_NONBLOCK;
if((s = fcntl(sfd, F_SETFL, flags)) == -1) {
perror ("make_socket_non_blocking (non_block): fcntl");
return -1;
}
return 0;
}
int set_reuseaddr(int sfd)
{
int optval = 1;
if(setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval))) {
perror ("set_reuseaddr (SO_REUSEADDR): setsockopt");
return -1;
}
return 0;
}
int set_nodelay(int sfd) {
int optval = 1;
if(setsockopt(sfd, SOL_SOCKET, TCP_NODELAY, &optval, sizeof(optval))) {
perror ("set_reuseaddr (SO_REUSEADDR): setsockopt");
return -1;
}
return 0;
}
int create_server(int port)
{
struct addrinfo hints;
struct addrinfo *result, *rp;
int s, sfd;
char port_str[12] = {'\0'};
sprintf(port_str, "%d", port);
memset(&hints, 0, sizeof (struct addrinfo));
hints.ai_family = AF_UNSPEC; /* Return IPv4 and IPv6 choices */
hints.ai_socktype = SOCK_STREAM; /* We want a TCP socket */
hints.ai_flags = AI_PASSIVE; /* All interfaces */
if((s = getaddrinfo(NULL, port_str, &hints, &result)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror (s));
return -1;
}
for(rp = result; rp != NULL; rp = rp->ai_next) {
if ((sfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol)) == -1)
continue;
if(set_reuseaddr(sfd) == -1)
abort();
if((s = bind(sfd, rp->ai_addr, rp->ai_addrlen)) == 0)
break;
close(sfd);
}
if(rp == NULL) {
fprintf(stderr, "Could not bind\n");
return -1;
}
if ((s = make_socket_non_blocking(sfd)) == -1)
return -1;
if((s = listen(sfd, SOMAXCONN)) == -1) {
perror("listen");
return -1;
}
freeaddrinfo(result);
printf("Server started on port %d using fd %d\n", port, sfd);
return sfd;
}