Friday, January 30, 2009

Mistakes, not to be forgotten

Socket Programming:

Was writing a socket server few days back. The code was not working, it goes like(omitting error checks)

SOCKET g_sock_server;
g_sock_server = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
bind(g_sock_server, (LPSOCKADDR) &g_addr_server, sizeof(g_addr_server));
listen(g_sock_server, SOMAXCONN);

SOCKADDR_IN addr_cli;
SOCKET s_cli;
int nSize = 0;
s_cli = accept(g_sock_server, (LPSOCKADDR)&addr_cli, &nSize);
if(s_cli == INVALID_SOCKET) return;
// rest of the code... say blah blah blah blah

The method accept will always return INVALID_SOCKET, guess why?

because of

int nSize = 0;

The fix is

int nSize = sizeof(addr_cli)

cheers all...

No comments:

Post a Comment

Feel free to talk back...