Search code examples
c++winsock

winsock "invalid argument" error on listen


I was trying to make a simple client - server communication application, but I've come across a problem - I get error 10022 ( invalid argument ) on listen.

WSADATA wsaData;
int iResult;
sockaddr_in addr;
SOCKET sock, client;
addr.sin_family = AF_INET;
addr.sin_port = htons( 25565 );
addr.sin_addr.S_un.S_addr = inet_addr( "127.0.0.1" );

iResult = WSAStartup( MAKEWORD( 2, 2 ), &wsaData );

if( iResult )
{
    std::cout << ( WSAGetLastError( ) );
    _getch( );
}

sock = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );

if( sock == INVALID_SOCKET )
{
    std::cout << ( WSAGetLastError( ) );
    _getch( );
}

iResult = listen( sock, SOMAXCONN );

if( iResult )
{
    std::cout << ( WSAGetLastError( ) );
    _getch( );
}

Solution

  • Before you listen, you need to bind the socket to the port that will be listened on.

    It looks like you have already built the address structure containing the information necessary to bind, so call bind(sock, &addr, sizeof(addr)) and perform appropriate error checking before the call to listen.

    Documentation for bind