Aaron
Aaron

Reputation: 2873

why bind() returns SOCKET_ERROR

Without:

Using pure C++, WSAGetLastError() returns 10014 - Bad address

Code illustration:

sockaddr_in sin;
SOCKET server;

if ((server = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == SOCKET_ERROR)
{
    cerr << "Error: socket() return value == SOCKET_ERROR" << endl;
    WSACleanup();
    exit (EXIT_FAILURE);
}

sin.sin_family = AF_INET;
sin.sin_addr.s_addr = INADDR_ANY;
sin.sin_port = htons(1234); //random port

if(bind(server, (sockaddr *)&sin, sizeof(sin) == SOCKET_ERROR))
{
    wError = WSAGetLastError();
    cerr << "Error: bin() return value == SOCKET_ERROR\n"
            "Details: " << wError << endl;
    WSACleanup();
    exit (EXIT_FAILURE);
}

Upvotes: 1

Views: 5814

Answers (1)

paxdiablo
paxdiablo

Reputation: 881423

If that's your real code, you've got the brackets in the wrong place in the bind call. One of the two at the end should be moved to immediately after the "sizeof(sin)".

In other words, change it from:

if(bind(server, (sockaddr *)&sin, sizeof(sin) == SOCKET_ERROR))

to:

if(bind(server, (sockaddr *)&sin, sizeof(sin)) == SOCKET_ERROR)

This is a subtle C error unrelated to socket programming but illustrates how you need to be careful when using a language that makes it easy to have have syntactically-correct statements that are semantically incorrect.

The way you have it, it's calculates "sizeof(sin) == SOCKET_ERROR" (which is always false (zero) since sizeof(something) is always one or more and SOCKET_ERROR is always -1, at least for WinSock).

It then passes this zero as the third argument to bind() which naturally complains that you haven't given a big-enough size for the address structure.

And, because of that, bind() is returning a non-zero error code, which is why your if-block is executing.

A very subtle one. My respect for the C language remains high, even though I've been using it for 20-odd years - respect in the sense of "I respect lions when I'm in the Serengeti" rather than "I respect my wife's opinions" :-)

Upvotes: 6

Related Questions