-
Notifications
You must be signed in to change notification settings - Fork 0
/
tcpbind.c
40 lines (34 loc) · 869 Bytes
/
tcpbind.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
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <syslog.h>
#include <strings.h>
int tcpbind(const char *ip, int port)
{
int fd, opt;
struct sockaddr_in a;
if ((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
syslog(LOG_ERR, "failed to create tcp socket");
return -1;
}
opt = 1;
if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < 0) {
syslog(LOG_ERR, "failed to set socket options: %m");
return -1;
}
bzero(&a, sizeof(a));
a.sin_addr.s_addr = inet_addr(ip);
a.sin_port = htons(port);
a.sin_family = AF_INET;
if (bind(fd, (struct sockaddr *) &a, sizeof(a)) < 0) {
syslog(LOG_ERR, "binding to address %s:%d failed: %m",
ip, port);
return -1;
}
#define LISTENQ 1024
if (listen(fd, LISTENQ) < 0) {
syslog(LOG_ERR, "failed to set listen queue of %d", LISTENQ);
return -1;
}
return fd;
}