views:

183

answers:

2

I have quite an embarrassing problem. The following code simply will not create a socket on Windows; it fails and displays the error message. Could anyone briefly explain why this might be? I'm incredibly confused and frustrated that something so simple is failing. Thank you.

int sock;
if( (sock = socket(AF_INET, SOCK_STREAM, 0)) < 0 )
{
    printf("error opening socket");
}

EDIT: Also, printing out strerror(errno) simply shows "No error".

+3  A: 

You need to call WSAStartup() before any other socket functions will work on Windows (and you're supposed to call WSACleanup() when you're done).

Jerry Coffin
Thank you...somehow I have been getting winsock to work all this time without using that function. Very strange.
oskar
You are probably usually using some other component that needs to use sockets and which is doing the startup for you...
Len Holgate
+2  A: 

Jerry Coffin is right about WSAStartup() and WSACleanup().

Also note that this code

if( (sock = socket(AF_INET, SOCK_STREAM, 0)) < 0 )

is problematic because SOCKET is an unsigned type (unsigned int).

From winsock.h

/*
 * This is used instead of -1, since the
 * SOCKET type is unsigned.
 */
#define INVALID_SOCKET  (SOCKET)(~0)
#define SOCKET_ERROR            (-1)

So, IMO it's better to replace that line with

if( INVALID_SOCKET == (sock = socket(AF_INET, SOCK_STREAM, 0)) )

even if it's not the root cause.

Nick D