-
Notifications
You must be signed in to change notification settings - Fork 1
/
tcp_conn.c
68 lines (55 loc) · 1.14 KB
/
tcp_conn.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
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <net/if.h>
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include "clog.h"
static int set_non_block(int fd)
{
int flags;
flags = fcntl(fd, F_GETFL, 0);
if (flags == -1)
return -1;
return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
}
static void set_server_socket(int fd)
{
int used = 1;
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &used, sizeof(used));
set_non_block(fd);
}
int tcp_start(int port)
{
int ret;
struct sockaddr_in saddr;
int fd;
fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd < 0) {
clog(CL_ERROR, "Create socket failed\n");
return -1;
}
set_server_socket(fd);
saddr.sin_family = AF_INET;
saddr.sin_addr.s_addr = htonl(INADDR_ANY);
saddr.sin_port = htons(port);
ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
if (ret < 0) {
clog(CL_ERROR, "Bind to socket failed\n");
goto bad_fd;
}
ret = listen(fd, 5);
if (ret < 0) {
clog(CL_ERROR, "Listen on socket failed\n");
goto bad_fd;
}
return fd;
bad_fd:
close(fd);
return -1;
}