0

It probably has nothing to do with it, but I'm grappling with converting an old MFC app to Unicode. I thought I might try making another completely new MFC app using a Unicode character set just to get some things clear in my head. Besides which, I needed a little tool to talk to a PLC using UDP, so I thought I'd use that as a test case.

So the new MFC Unicode app is going fine... until I cut and paste the following in from the old app:

if ( ( mySocket = socket( AF_INET, SOCK_DGRAM, IPPROTO_UDP ) ) == INVALID_SOCKET )
{
    throw std::string( "Failed to open UDP socket" );
}

That line has never caused a problem when the old app was deployed on WinXP, Win7 (32- or 64-bit) or Win8, compiled using Visual Studio 2005 or 2010.

But my motivation for the Unicode conversion is Visual Studio 2013. I compile on that as a Win32 target, and it compiles fine, but when I run my new app on Win7 or Win8 (both 64-bit; haven't tried anything else), it always throws an error at this point. Why?

omatai
  • 3,448
  • 5
  • 47
  • 74
  • What error does it give? – David G Mar 30 '15 at 20:49
  • 2
    Why are you not calling `WSAGetLastError`? It not only has the last error, but a combination of that function along with `FormatMessage` gives you the error as a string. http://stackoverflow.com/questions/4633410/get-formatted-message-for-wsa-error-codes – PaulMcKenzie Mar 30 '15 at 20:49
  • What does `WSAGetLastError()` return? – Anton Savin Mar 30 '15 at 20:49
  • Note: when you can get UDP socket with only 2 args: `socket( AF_INET, SOCK_DGRAM, 0)`. You don't need that 3rd param – Sly_TheKing Mar 30 '15 at 21:02
  • Behold the problem with doing 90% of your network programming on Unix, and years ago, and failing to see the single magic mushroom that enabled all the trees to be a forest. The error was 10093 - Winsock was not initialised. Obvious when you know it... and know about WSAGetLastError() - thanks :-) – omatai Mar 30 '15 at 21:26

1 Answers1

2

The code you showed is fine by itself, but you did not specify the error code that WSAGetLastError() reports when socket() fails:

Return value
If no error occurs, socket returns a descriptor referencing the new socket. Otherwise, a value of INVALID_SOCKET is returned, and a specific error code can be retrieved by calling WSAGetLastError.

The most likely error code in this situation is WSANOTINITIALISED (10093):

Successful WSAStartup not yet performed.
Either the application has not called WSAStartup or WSAStartup failed. The application may be accessing a socket that the current active task does not own (that is, trying to share a socket between tasks), or WSACleanup has been called too many times.

Since you are starting a new project, it is likely that you simply forgot to call WSAStartup() to initialize the Winsock library before calling socket().

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