3

以下是我编写的用于捕获来自多播地址 ff02::1 和端口 9154 的 IPv6 多播数据的函数。
此代码在 Windows Vista 和 Windows 7 上运行良好。但我无法为 Windows 8 捕获相同的流量(没有winsock函数返回 Win8 的错误)。

使用netstat我能够验证我的应用程序是否正在使用此端口。
任何人都可以帮忙吗?

void func()
{

    int multicastChannel = 0;
    char multicastIP[] = "FF02::1";
    char multicastPort[] = "9154";

    ADDRINFO*  multicastAddr  = NULL;
    ADDRINFO*  localAddr      = NULL;
    ADDRINFO   hints          = { 0 };

    struct ipv6_mreq multicastRequest6;

    hints.ai_family = PF_UNSPEC;
    hints.ai_flags  = AI_NUMERICHOST;

    if ( getaddrinfo(multicastIP, NULL, &hints, &multicastAddr) != 0 )
    {
        printf("getaddrinfo() failed");
        return;
    }

    hints.ai_family   = multicastAddr->ai_family;
    hints.ai_socktype = SOCK_DGRAM;
    hints.ai_flags    = AI_PASSIVE;

    if ( getaddrinfo(NULL, multicastPort, &hints, &localAddr) != 0 )
    {
        printf("getaddrinfo() failed");
        return;
    }

    multicastChannel = socket(localAddr->ai_family, localAddr->ai_socktype, 0);

    if ( bind(multicastChannel, localAddr->ai_addr, localAddr->ai_addrlen) != 0 )
    {
        printf("bind() failed");
        return;
    }

    memcpy(&multicastRequest6.ipv6mr_multiaddr,
           &((struct sockaddr_in6*)(multicastAddr->ai_addr))->sin6_addr,
           sizeof(multicastRequest6.ipv6mr_multiaddr));

    multicastRequest6.ipv6mr_interface = 0;

    if ( setsockopt(multicastChannel,
                    IPPROTO_IPV6,
                    IPV6_ADD_MEMBERSHIP,
                    (char*) &multicastRequest6,
                    sizeof(multicastRequest6)) != 0 )
    {
        ERROR_ReportError("setsockopt() failed");
    }

    freeaddrinfo(localAddr);
    freeaddrinfo(multicastAddr);

    ioctlsocket(multicastChannel, FIONBIO, &arg);

    sockaddr_in6 fromAddr;

    while(1)
    {
        read = recvfrom(multicastChannel,
                data,
                1500,
                0,
                (struct sockaddr*)&fromAddr,
                &sizeof(sockaddr_in6);

        if (read > 0) {
            function();
        }
    }
}
4

0 回答 0