1 | #define _GNU_SOURCE |
---|
2 | |
---|
3 | #include "socket.hfa" |
---|
4 | |
---|
5 | #include <errno.h> |
---|
6 | #include <string.h> |
---|
7 | extern "C" { |
---|
8 | #include <sys/socket.h> |
---|
9 | #include <netinet/in.h> |
---|
10 | } |
---|
11 | |
---|
12 | #include <fstream.hfa> |
---|
13 | #include <time.hfa> |
---|
14 | #include <thread.hfa> |
---|
15 | |
---|
16 | #include "options.hfa" |
---|
17 | |
---|
18 | int prepaddr(struct sockaddr_in & address) { |
---|
19 | int addrlen = sizeof(address); |
---|
20 | memset( (char *)&address, '\0', addrlen ); |
---|
21 | address.sin_family = AF_INET; |
---|
22 | address.sin_addr.s_addr = htonl(INADDR_ANY); |
---|
23 | address.sin_port = htons( options.socket.port ); |
---|
24 | return addrlen; |
---|
25 | } |
---|
26 | |
---|
27 | int listener(struct sockaddr_in & address, int addrlen) { |
---|
28 | int sockfd = socket(AF_INET, SOCK_STREAM, 0); |
---|
29 | if(sockfd < 0) { |
---|
30 | abort( "socket error: (%d) %s\n", (int)errno, strerror(errno) ); |
---|
31 | } |
---|
32 | |
---|
33 | if(options.socket.onereuse || options.socket.manyreuse) { |
---|
34 | int value = 1; |
---|
35 | // if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const void*)&on, sizeof(on))) |
---|
36 | // abort( "setsockopt SO_REUSEADDR error: (%d) %s\n", (int)errno, strerror(errno) ); |
---|
37 | if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEPORT, &value, sizeof(int)) < 0) |
---|
38 | abort( "setsockopt SO_REUSEPORT error: (%d) %s\n", (int)errno, strerror(errno) ); |
---|
39 | } |
---|
40 | |
---|
41 | int ret = 0; |
---|
42 | int waited = 0; |
---|
43 | for() { |
---|
44 | __CONST_SOCKADDR_ARG addr; |
---|
45 | addr.__sockaddr__ = (struct sockaddr *)&address; |
---|
46 | socklen_t addrlen = sizeof(address); |
---|
47 | ret = bind( sockfd, addr, addrlen ); |
---|
48 | if(ret < 0) { |
---|
49 | if(errno == EADDRINUSE) { |
---|
50 | if(waited == 0) { |
---|
51 | if(!options.interactive) abort | "Port already in use in non-interactive mode. Aborting"; |
---|
52 | sout | "Waiting for port"; |
---|
53 | } else { |
---|
54 | sout | "\r" | waited | nonl; |
---|
55 | flush( sout ); |
---|
56 | } |
---|
57 | waited ++; |
---|
58 | sleep( 1`s ); |
---|
59 | continue; |
---|
60 | } |
---|
61 | abort( "bind error: (%d) %s\n", (int)errno, strerror(errno) ); |
---|
62 | } |
---|
63 | break; |
---|
64 | } |
---|
65 | |
---|
66 | ret = listen( sockfd, options.socket.backlog ); |
---|
67 | if(ret < 0) { |
---|
68 | abort( "listen error: (%d) %s\n", (int)errno, strerror(errno) ); |
---|
69 | } |
---|
70 | |
---|
71 | return sockfd; |
---|
72 | } |
---|