views:

648

answers:

1

Without:

  • MFC
  • ATL

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

  • What I'm I missing/doing wrong?

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);
}
+5  A: 

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" :-)

paxdiablo
I can't believe it...... :(
Aaron
Should I delete this post?
Aaron
I don't believe posts should be deleted unless they're spam or waffly questions with no real answers. This one's fairly localized but it's possible other people may have the same problem. But, it's your question and your decision.
paxdiablo
In reality, it wasn't a bind() problem but one of C's nigglies - the possibility that something syntactically correct is semantically incorrect - the same reason I don't trust spellcheckers since they won't catch things like "I bent shopping yesterday" or "I bought this disk into work today".
paxdiablo
I'd leave it here as an example of how C can burn you if you're not eternally vigilant. C is a chainsaw whilst most other languages are staplers (my jury is still out as to which is better :-).
paxdiablo