0

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

2 Answers2

3

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

user4581301
  • 33,082
  • 7
  • 33
  • 54
2

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.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770