Home > Net >  Can't bind winsock socket
Can't bind winsock socket

Time:09-23

I'm quite new to c networking so I've been watching some tutorials but I can't seem to find out why I can't bind my socket. Can someone explain to me what I'm doing wrong? Here's my code for binding the socket.

#include <stdlib.h>
#include <winsock2.h>

#pragma comment (lib,"ws2_32.lib")
#pragma warning( disable : 4996)
#define PORT 17027
int main()
{
    //creating socket
    SOCKET listenSocket = INVALID_SOCKET;
    listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

    //bind socket
    struct sockaddr_in address;
    memset(&address, 0, sizeof(address));
    address.sin_family = AF_INET;
    address.sin_port = htons(PORT);

    int bindValue = bind(listenSocket, (struct sockaddr *)&address, sizeof(address));
    if (bindValue == SOCKET_ERROR) {
        std::cout << WSAGetLastError() << std::endl; 
        return 1;
    }

Output: Could not bind: 10038

CodePudding user response:

Error 10038 is WSAENOTSOCK ("Socket operation on nonsocket"), which means you are calling bind() on an invalid SOCKET. And indeed, you are not checking if socket() is successful. Which it is not, as you are not calling WSAStartup() first, so socket() is failing with a WSANOTINITIALISED error ("Successful WSAStartup not yet performed").

The WSAStartup function must be the first Windows Sockets function called by an application or DLL. It allows an application or DLL to specify the version of Windows Sockets required and retrieve details of the specific Windows Sockets implementation. The application or DLL can only issue further Windows Sockets functions after successfully calling WSAStartup.

CodePudding user response:

You must state which interface you want to bind the socket to. This is done by setting the sin_addr member of the sockaddr_in structure.

For example, to bind to the wildcard interface INADDR_ANY (to be able to receive connections from all interfaces), you would do something like this:

address.sin_addr.s_addr = htonl(INADDR_ANY);

Whereas to bind to a specific interface, you would do something like this:

address.sin_addr.s_addr = inet_addr("interface IP here");

Regarding the error reporting, the Winsock API doesn't set errno for error (and errno is used by perror()). Instead, you need to use WSAGetLastError() to get the error code, and FormatMessage() to get the error description.

  • Related