source: benchmark/io/http/socket.cfa @ ac1aba4b

ADTast-experimentalpthread-emulationqualifiedEnum
Last change on this file since ac1aba4b was c4b10e2, checked in by Thierry Delisle <tdelisle@…>, 2 years ago

Moved socket creation to a different file.
Makefile now has debug symbol.
Pipes are now closed earlier for a cleaner exit.

  • Property mode set to 100644
File size: 1.6 KB
Line 
1#define _GNU_SOURCE
2
3#include "socket.hfa"
4
5#include <errno.h>
6#include <string.h>
7extern "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
18int 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
27int 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        int value = 1;
34        if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &value, sizeof(int)) < 0)
35                abort( "setsockopt error: (%d) %s\n", (int)errno, strerror(errno) );
36
37        int ret = 0;
38        int waited = 0;
39        for() {
40                __CONST_SOCKADDR_ARG addr;
41                addr.__sockaddr__ = (struct sockaddr *)&address;
42                socklen_t addrlen = sizeof(address);
43                ret = bind( sockfd, addr, addrlen );
44                if(ret < 0) {
45                        if(errno == EADDRINUSE) {
46                                if(waited == 0) {
47                                        if(!options.interactive) abort | "Port already in use in non-interactive mode. Aborting";
48                                        sout | "Waiting for port";
49                                } else {
50                                        sout | "\r" | waited | nonl;
51                                        flush( sout );
52                                }
53                                waited ++;
54                                sleep( 1`s );
55                                continue;
56                        }
57                        abort( "bind error: (%d) %s\n", (int)errno, strerror(errno) );
58                }
59                break;
60        }
61
62        ret = listen( sockfd, options.socket.backlog );
63        if(ret < 0) {
64                abort( "listen error: (%d) %s\n", (int)errno, strerror(errno) );
65        }
66
67        return sockfd;
68}
Note: See TracBrowser for help on using the repository browser.