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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
|
#include "epoll_server.h"
#include <netdb.h>
#include <stdlib.h>
#include <sys/epoll.h>
#include <sys/socket.h>
#include <unistd.h>
#include "connection.h"
#include "string.h"
int create_and_bind(struct addrinfo *addrinfo)
{
for (struct addrinfo *info = addrinfo; info != NULL; info = info->ai_next)
{
int sock_fd =
socket(info->ai_family, info->ai_socktype, info->ai_protocol);
if (sock_fd != -1)
{
int feur = bind(sock_fd, info->ai_addr, info->ai_addrlen);
if (feur != -1)
{
return sock_fd;
}
else
{
close(sock_fd);
}
}
}
exit(1);
}
int prepare_socket(const char *ip, const char *port)
{
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
struct addrinfo *addrinfo;
int e = getaddrinfo(ip, port, &hints, &addrinfo);
if (e != 0)
{
exit(1);
}
e = create_and_bind(addrinfo);
int e2 = listen(e, 1000);
freeaddrinfo(addrinfo);
if (e2 == -1)
{
close(e);
exit(1);
}
return e;
}
struct connection_t *accept_client(int epoll_instance, int server_socket,
struct connection_t *connection)
{
int e = accept(server_socket, NULL, 0);
if (e == -1)
{
close(server_socket);
exit(1);
}
struct epoll_event tmp;
tmp.events = EPOLLIN;
tmp.data.fd = e;
int er = epoll_ctl(epoll_instance, EPOLL_CTL_ADD, e, &tmp);
if (er == -1)
{
close(server_socket);
close(e);
exit(1);
}
return add_client(connection, e);
}
int main(int argc, char **argv)
{
if (argc != 3)
{
exit(1);
}
int epoll_instance = epoll_create1(0);
if (epoll_instance == -1)
{
exit(1);
}
int e = prepare_socket(argv[1], argv[2]);
struct connection_t *co = NULL;
struct epoll_event tmp;
tmp.events = EPOLLIN;
tmp.data.fd = e;
if (epoll_ctl(epoll_instance, EPOLL_CTL_ADD, e, &tmp) == -1)
{
close(e);
exit(1);
}
while (1)
{
struct epoll_event elist[MAX_EVENTS];
int info = epoll_wait(epoll_instance, elist, MAX_EVENTS, -1);
if (info == -1)
{
exit(1);
}
for (int i = 0; i < info; i++)
{
int fd = elist[i].data.fd;
if (fd == e)
{
co = accept_client(epoll_instance, e, co);
}
else
{
char buf[100] = { 0 };
int info1 = recv(fd, buf, 100, 0);
if (info1 < 1)
{
co = remove_client(co, fd);
close(fd);
}
else
{
struct connection_t *tmp = co;
while (tmp != NULL)
{
send(tmp->client_socket, buf, info1, 0);
tmp = tmp->next;
}
}
}
}
}
}
|