7 #include <sys/socket.h>
8 #include <netinet/in.h>
17 #include "Listener.hpp"
20 #include "Exceptions.hpp"
27 WSAStartup( MAKEWORD( 2, 2 ), &wsaData
);
30 // Discover machine's IP address
32 gethostname( buf
, 128 );
35 if( ( h
= gethostbyname( buf
) ) == (void*)-1 )
37 g_log
->Print( strerror( errno
) );
38 throw ServerCrashException
;
40 m_ipaddr
= inet_ntoa( *((in_addr
*)h
->h_addr
) );
43 Listener::Listener( const std::string
& ip
)
53 g_log
->Print( "[Listener] Closing socket" );
58 void Listener::Listen()
60 g_log
->Print( "[Listener] Opening socket" );
62 if( ( m_sock
= socket( PF_INET
, SOCK_STREAM
, 0 ) ) == -1 )
64 g_log
->Print( strerror( errno
) );
65 throw ServerCrashException
;
74 if( setsockopt( m_sock
, SOL_SOCKET
, SO_REUSEADDR
, &yes
, sizeof( int ) ) == -1 )
76 g_log
->Print( strerror( errno
) );
77 throw ServerCrashException
;
81 addr
.sin_family
= AF_INET
;
82 addr
.sin_port
= htons( 21 );
83 addr
.sin_addr
.s_addr
= inet_addr( m_ipaddr
.c_str() );
84 memset( addr
.sin_zero
, 0, sizeof( addr
.sin_zero
) );
86 if( bind( m_sock
, (sockaddr
*)&addr
, sizeof( addr
) ) == -1 )
88 g_log
->Print( strerror( errno
) );
89 throw ServerCrashException
;
92 if( listen( m_sock
, 5 ) == -1 )
94 g_log
->Print( strerror( errno
) );
95 throw ServerCrashException
;
101 // Check if there are some incoming connections
103 socklen_t size
= sizeof( addr
);
105 int incoming
= accept( m_sock
, (sockaddr
*)&addr
, &size
);
108 g_log
->Print( strerror( errno
) );
109 throw ServerCrashException
;
112 ServerPtr server
= m_server
.lock();
113 server
->IncomingConnection( incoming
);