-
Notifications
You must be signed in to change notification settings - Fork 0
/
listen_linux.c
101 lines (87 loc) · 1.75 KB
/
listen_linux.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
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
#include <errno.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/select.h>
#include "listen.h"
int serverfd;
struct sockaddr_in addr;
socklen_t addrlen;
char buffer[BUFFERSIZE];
int error (char * msg) {
int err = errno;
perror(msg);
return err;
}
int listen_Init ()
{
int err;
int opt = 1;
int flags = SO_REUSEADDR;
int backlog = 3;
addrlen = sizeof(addr);
memset(buffer, 0, BUFFERSIZE);
serverfd = socket(AF_INET, SOCK_STREAM, 0);
if (serverfd < 0)
return error("socket failed");
err = setsockopt(serverfd, SOL_SOCKET, flags, &opt, sizeof(opt));
if (err)
return error("setsockopt failed");
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_port = htons(PORT);
err = bind(serverfd, (struct sockaddr *)&addr, sizeof(addr));
if (err)
return error("bind failed");
err = listen(serverfd, backlog);
if (err)
return error("listen failed");
return 0;
}
int listen_Wait ()
{
int c = accept(serverfd, (struct sockaddr *)&addr, &addrlen);
if (c < 0)
return error("accept failed");
return c;
}
int listen_Read (int *fd)
{
if (*fd < 0)
return 0;
int n = 0;
int read = recv(*fd, &n, sizeof(int), 0);
#if DEBUG
printf("\tread (%d) from client=%d\n", n, *fd);
#endif
if (read <= 0) {
*fd = -1;
return 0;
}
return n;
}
int listen_SendMsg (int *fd, char *str)
{
if (*fd < 0)
return -1;
#if DEBUG
printf("\tsending '%s' to client=%d\n", str, *fd);
#endif
int n = send(*fd, str, MSGSIZE, MSG_NOSIGNAL);
if (n <= 0)
*fd = -1;
return n;
}
int listen_SendInt (int *fd, int n)
{
if (*fd < 0)
return -1;
#if DEBUG
printf("\tsending (%d) to client=%d\n", n, *fd);
#endif
int sent = send(*fd, &n, sizeof(int), MSG_NOSIGNAL);
if (sent <= 0)
*fd = 1;
return sent;
}