-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimple_net.c
69 lines (57 loc) · 1.54 KB
/
simple_net.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
/* code taken and adapted from http://www.ecst.csuchico.edu/~beej/guide/net/ */
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <signal.h>
#include <errno.h>
#include "simple_net.h"
int create_service(unsigned short port, int queue_size)
{
int fd; /* listen on sock_fd, new connection on new_fd */
struct sockaddr_in local_addr; /* my address information */
int yes=1;
if ((fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
return -1;
}
if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1)
{
return -1;
}
local_addr.sin_family = AF_INET; /* host byte order */
local_addr.sin_port = htons(port); /* short, network byte order */
local_addr.sin_addr.s_addr = INADDR_ANY; /* automatically fill with my IP */
memset(&(local_addr.sin_zero), '\0', 8); /* zero the rest of the struct */
if (bind(fd, (struct sockaddr *)&local_addr, sizeof(struct sockaddr)) == -1)
{
return -1;
}
if (listen(fd, queue_size) == -1)
{
return -1;
}
return fd;
}
int accept_connection(int fd)
{
int new_fd;
struct sockaddr_in remote_addr;
socklen_t size = sizeof(struct sockaddr_in);
errno = EINTR;
while (errno == EINTR)
{
if ((new_fd = accept(fd, (struct sockaddr*)&remote_addr, &size)) == -1
&& errno != EINTR)
{
return -1;
}
else if (new_fd != -1)
{
break;
}
}
return new_fd;
}