-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinit_listener.cpp
More file actions
68 lines (53 loc) · 1.58 KB
/
init_listener.cpp
File metadata and controls
68 lines (53 loc) · 1.58 KB
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
#include "init_listener.hpp"
#include "configuration.hpp"
#include "logger.hpp"
#include <netdb.h>
#include <cstring>
#include <unistd.h>
#include <cerrno>
extern Log main_log;
static Socket openSocket()
{
addrinfo hints, *result, *rp;
/* The port to attempt binding to */
int port = std::stoi ( get_config ( "port" ) );
memset ( &hints,0,sizeof ( addrinfo ) );
hints.ai_socktype = SOCK_STREAM;
hints.ai_family = AF_UNSPEC;
hints.ai_flags = AI_PASSIVE | AI_NUMERICSERV;
if ( getaddrinfo ( NULL,std::to_string ( port ).c_str(),&hints,&result ) == -1 ) {
main_log << ERROR << "Error getting valid sockets. See "
<< __FILE__ <<", line #" << __LINE__ << "\n";
throw 10;
}
for ( rp = result; rp ; rp = rp->ai_next ) {
try {
Socket s(rp->ai_family,rp->ai_socktype,0);
main_log << DEBUG << "Created socket.\n";
SocketAddress sa;
sa.address = rp->ai_addr;
sa.length = rp->ai_addrlen;
try {
s.bind(sa);
main_log << DEBUG << "Bound socket onto address "
<< rp->ai_addr->sa_data << "\n";
freeaddrinfo(result); // Ideally this should be RAII
return s;
}
catch (int &e) {
main_log << DEBUG << "Attempt to bind to socket failed.\n";
main_log << DEBUG << strerror(errno) << "\n";
}
}
catch (int &e) {} // If an exception is thrown, we simply try again
}
freeaddrinfo(result);
throw; //TODO: better exception
}
Listener::Listener ( int backlog )
: Socket(openSocket())
{
listen(backlog);
main_log << INFO << "Initted listener on port " << get_config( "port" )
<< "with fd " << getfd() << "\n";
}