8 #include <sys/socket.h>
9 #include <netinet/in.h>
10 #include <arpa/inet.h>
11 #include "Listener.hpp"
14 #include "Exceptions.hpp"
19 // Discover machine's IP address
21 gethostname( buf
, 128 );
24 if( ( h
= gethostbyname( buf
) ) == (void*)-1 )
26 g_log
->Print( strerror( errno
) );
27 throw ServerCrashException
;
29 m_ipaddr
= inet_ntoa( *((in_addr
*)h
->h_addr
) );
32 Listener::Listener( const std::string
& ip
)
42 g_log
->Print( "[Listener] Closing socket" );
47 void Listener::Listen()
49 g_log
->Print( "[Listener] Opening socket" );
51 if( ( m_sock
= socket( PF_INET
, SOCK_STREAM
, 0 ) ) == -1 )
53 g_log
->Print( strerror( errno
) );
54 throw ServerCrashException
;
59 if( setsockopt( m_sock
, SOL_SOCKET
, SO_REUSEADDR
, &yes
, sizeof( int ) ) == -1 )
61 g_log
->Print( strerror( errno
) );
62 throw ServerCrashException
;
66 addr
.sin_family
= AF_INET
;
67 addr
.sin_port
= htons( 21 );
68 addr
.sin_addr
.s_addr
= inet_addr( m_ipaddr
.c_str() );
69 memset( addr
.sin_zero
, 0, sizeof( addr
.sin_zero
) );
71 if( bind( m_sock
, (sockaddr
*)&addr
, sizeof( addr
) ) == -1 )
73 g_log
->Print( strerror( errno
) );
74 throw ServerCrashException
;
77 if( listen( m_sock
, 5 ) == -1 )
79 g_log
->Print( strerror( errno
) );
80 throw ServerCrashException
;
86 // Check if there are some incoming connections
88 socklen_t size
= sizeof( addr
);
90 int incoming
= accept( m_sock
, (sockaddr
*)&addr
, &size
);
93 g_log
->Print( strerror( errno
) );
94 throw ServerCrashException
;
97 ServerPtr server
= m_server
.lock();
98 server
->IncomingConnection( incoming
);