setsockopt 失败并且 returns -1

setsockopt fails and returns -1

我正在尝试 运行 一个演示使用 GSOAP 的发现功能的示例。不幸的是,我似乎在 setsockopt 上得到了 -1 关于为什么会发生这种情况的任何建议?错误号是无效的参数。

const char* host = "127.0.0.1"; 
int port = 3702;
const int   _metadataVersion = 1;
const char* _xaddr="http://localhost/service";
const char* _type="\"http://schemas.xmlsoap.org/ws/2006/02/devprof\":device";
const char* _scope="scope";
const char* _endpoint="urn";

int main(int argc, char** argv)
{
    struct soap* serv = soap_new1(SOAP_IO_UDP); 
    serv->bind_flags=SO_REUSEADDR;
    if (!soap_valid_socket(soap_bind(serv, NULL, port, 1000)))
    {
        std::cout << "Error in Bind \n";
        soap_print_fault(serv, stderr);
        exit(1);
    }   
    ip_mreq mcast; 
    mcast.imr_multiaddr.s_addr = inet_addr(host);
    mcast.imr_interface.s_addr = htonl(INADDR_ANY);
    int res = setsockopt(serv->master, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mcast, sizeof(mcast));
        std::cout << "setsockopt returned " << res << "\n";
        if(res < 0) 
    //if (setsockopt(serv->master, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mcast, sizeof(mcast))<0) 
    {
        std::cout << "group membership failed:" << strerror(errno) << std::endl;  //The error no is invalid Argument
        exit(1);        
    }   

    sendHello();
    mainloop(serv);

    signal(SIGINT, &sighandler);
    while (!stop)
    {
        mainloop(serv);
    }

    sendBye();
    mainloop(serv);

    return 0;
}

host = "127.0.0.1",应该是一个有效的multicast address,从224.0.0.0239.255.255.255


以下三种方法可以帮助您分析这个问题。

  • 确保 host 的地址是一个有效的多播地址。

  • 使用ifconfig wlan0或任何其他界面,您可以检查MultiCast是否正确启用。

  • 用下面的代码检查组播地址是否正确。

    struct sockaddr_in sa;
    if (-1 == inet_pton(AF_INET, host/*such as 192.0.2.33*/, &sa.sin_addr))
         error("cannot set multicast address: %s\n", strerror(errno));
    memcpy(&mreq.imr_multiaddr.s_addr, (void*)&sa.sin_addr, sizeof(struct in_addr));
    mreq.imr_interface.s_addr = htonl(INADDR_ANY);