Jonathan Doagh
Jonathan Doagh

Reputation: 13

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( );
}

Upvotes: 0

Views: 232

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 595369

The answer is in the listen() documentation:

WSAEINVAL

The socket has not been bound with bind.

You need to bind() the socket before you can listen() on it.

Upvotes: 2

user4581301
user4581301

Reputation: 33932

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

Upvotes: 3

Related Questions