为什么 socket( AF_INET, SOCK_DGRAM, IPPROTO_UDP ) 会失败?

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

它可能与它无关,但我正在努力将旧的 MFC 应用程序转换为 Unicode。我想我可能会尝试使用 Unicode 字符集制作另一个全新的 MFC 应用程序,只是为了让我头脑清楚一些事情。除此之外,我需要一个小工具来使用 UDP 与 PLC 通信,所以我想我会用它作为测试用例。

所以新的 MFC Unicode 应用程序运行良好...直到我从旧应用程序中剪切并粘贴以下内容:

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

在使用 Visual Studio 2005 或 2010 编译的 WinXP、Win7(32 位或 64 位)或 Win8 上部署旧应用程序时,该行从未导致问题。

但我进行 Unicode 转换的动机是 Visual Studio 2013。我将其编译为 Win32 目标,并且编译正常,但是当我 运行 我的新应用程序在 Win7 或 Win8 上时(都是 64 位;还没有尝试过其他任何东西),此时它总是会抛出错误。为什么?

您显示的代码本身没有问题,但您没有指定 WSAGetLastError() reports when socket() 失败的错误代码:

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.

这种情况下最有可能的错误代码是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.

由于您正在开始一个新项目,您很可能只是忘记了在调用 socket() 之前调用 WSAStartup() 来初始化 Winsock 库。