Can't create socket on Windows

后端 未结 3 1606
猫巷女王i
猫巷女王i 2021-02-15 12:53

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 th

3条回答
  •  感动是毒
    2021-02-15 13:07

    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.

提交回复
热议问题