首页 > 解决方案 > C++ Windows 中的原始套接字

问题描述

我想RAW Socket在 Visual C++ 中使用 a 。

我看到了一个Linux函数

int out = socket(AF_INET, SOCK_RAW, htons(ETH_P_ALL));

在中使用此代码linux我们可以做到这一点,但是如何在 Windows 平台上使用 RAW SOCKET,因为当我在 Visual C++ 中使用它时,我得到了错误。

提前致谢。

编辑

int out1 = socket(AF_INET, SOCK_RAW, IPPROTO_SCTP);
for (; ;)
{
    int bytesIn = recvfrom(out1, buf, 2000, 0, (sockaddr*)&server, &serverLength);
    if (bytesIn == SOCKET_ERROR)
    {
        cout << "Error Receving from Server" << WSAGetLastError() << endl;
    }
    else
    {
        cout << "MESSAGE RECV from Server " << " : " << bytesIn << endl;
    }
}

这是我接收数据包的代码

标签: c++socketsudppackets

解决方案


在 Windows 中,最接近的等价物是SOCK_RAW,您必须使用一种技术来使您的代码跨平台兼容。

例如,使用宏并将基本通用虚拟类扩展为 Windows 派生类和 linux 派生类,使用Windows 的WSAPROTOCOL和 Linux 的 POSIX 库。

这是有关如何在Winsock 中使用原始套接字的指南。这是关于如何使用宏识别平台的答案。


推荐阅读