int init_sock ()
{
int err;
#ifdef WIN32
//Initialize environment for socket
WSADATA data;
err = WSAStartup (MAKEWORD (2, 2), &data);
if (err < 0)
exit (-1);
#endif
accept_ = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (INVALID_SOCKET == accept_)
{
//print error informations
cerr << "Error create a socket" << endl;
exit (-1);
}
///If we did't set the port, it will use the default port
port_ = Config_handler::get_int ("Network", "Snap_Port", 0);
if (port_ == 0)
port_ = PORT;
struct sockaddr_in sin;
memset (&sin, 0, sizeof(sin));
sin.sin_addr.s_addr = INADDR_ANY;
sin.sin_family = AF_INET;
sin.sin_port = htons (port_);
cerr << "Begin accept connection from known host." << endl;
while (processing_)
{
struct sockaddr_in sin;
socklen_t len = sizeof (sin);
SSL_SOCKET client = accept (accept_, (sockaddr*)&sin, &len);
if (INVALID_SOCKET != client)
{
//check the connection, it must connected
char ip[16];
sprintf (ip, "%u.%u.%u.%u", NIPQCHAR (sin.sin_addr.s_addr));
cerr << "Commint a connection from " << ip << endl;
//verify the connection
Connection_handler* h = Connection_handler::get_handler_ip (ip);
if (NULL == h)
{
cerr << "Unknown host ip(" << ip << "), refuse it" << endl;
shutdown (client, SHUT_RDWR);//CLOSESOCKET (client);//OK here if I shutdown or close the socket, the client will quit when it want to send something
}
else
{
arg_struct* args = new arg_struct ();
args->ibox = h->get_iboxid ();
args->sock = client;
THREAD_TYPE pid;
THREAD_CREATE (pid, do_connection, args);//thus create a thread
}
}
Sleep (0);
}