ICMPv6 套接字创建失败

ICMPv6 socket failed to create

我正在尝试将 ICMPV6 消息发送到远程网络,作为第一步,我尝试在一个简单的 class (SendICMPv6.c) 中创建一个 ICMPv6 套接字,其中包含 winsock2ws2tcpipstdiostdlib headers。但是我无法创建套接字。有人可以帮忙吗?

密码是:

WSADATA  wsaData;
int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (iResult != 0) {
        wprintf(L"WSAStartup failed: %d\n", iResult);
        return 1;
    }
int fd = socket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6);
    if (fd < 0) {
        perror("creating socket failed");
    }

有人能解决问题吗?

如果您仔细阅读 documentation,您可以检查的选项很少:

  1. 您的 OS 可以创建 SOCK_RAW 个套接字吗?

    If a Winsock service provider supports SOCK_RAW sockets for the AF_INET or AF_INET6 address families, the socket type of SOCK_RAW should be included in the WSAPROTOCOL_INFO structure returned by WSAEnumProtocols function for one or more of the available transport providers.

  2. 您运行是管理员吗?

    Therefore, only members of the Administrators group can create sockets of type SOCK_RAW on Windows 2000 and later.

您需要在代码中添加更多错误检查。例如,如果 socket() 失败:

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.

SOCK_RAW 需要管理员权限。您的应用 运行 是否处于提升状态?

socket()失败时,使用WSAGetLastError()查找原因,例如:

WSADATA wsaData;
int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
    printf("WSAStartup failed: %d\n", iResult);
    return 1;
}

SOCKET fd = socket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6);
if (fd == INVALID_SOCKET) {
    printf("creating socket failed: %d\n", WSAGetLastError());
    return 1;
}