omatai
omatai

Reputation: 3728

Why will socket( AF_INET, SOCK_DGRAM, IPPROTO_UDP ) fail?

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?

Upvotes: 0

Views: 3399

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 598001

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().

Upvotes: 2

Related Questions