setsockopt失败并返回-1

时间:2016-01-19 02:10:58

标签: c++ linux sockets gsoap

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

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;
}

1 个答案:

答案 0 :(得分:2)

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);