场景
需要开发一个服务器发现模块,等待客户端的探测报文。在Linux服务器下组播地址imr_interface可以不绑定
mcast.imr_multiaddr.s_addr = inet_addr(“239.255.255.250”);
mcast.imr_interface.s_addr = htonl(INADDR_ANY);
但是在windwos服务器下必须绑定一个指定的IP地址,否则无法收到任何的组播探测包
具体代码
//加入设备组,设备发现
DWORD WINAPI OnvifBeDiscovered(LPVOID p)
{
struct soap UDPserverSoap;
struct ip_mreq mcast;
soap_init1(&UDPserverSoap, SOAP_IO_UDP | SOAP_XML_IGNORENS);
soap_set_namespaces(&UDPserverSoap, namespaces);
SOAP_SOCKET localSocket = soap_bind(&UDPserverSoap, NULL, 3702, 10);
if (!soap_valid_socket(localSocket))
{
soap_print_fault(&UDPserverSoap, stderr);
exit(1);
}
mcast.imr_multiaddr.s_addr = inet_addr(“239.255.255.250”);
mcast.imr_interface.s_addr = inet_addr(“192.168.58.173”);
//IP_ADD_MEMBERSHIP用于加入某个多播组,之后就可以向这个多播组发送数据或者从多播组接收数据
if (setsockopt(UDPserverSoap.master, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char*)&mcast, sizeof(mcast)) < 0)
{
printf(“setsockopt error! error code = %d,err string = %s\n”, errno, strerror(errno));
return 0;
}
SOAP_SOCKET clientSocket = -1;
while (1)
{
clientSocket = soap_accept(&UDPserverSoap);
if (!soap_valid_socket(clientSocket))
{
soap_print_fault(&UDPserverSoap, stderr);
exit(1);
}
if (soap_serve(&UDPserverSoap) != SOAP_OK)
{
soap_print_fault(&UDPserverSoap, stderr);
}
soap_destroy(&UDPserverSoap);
soap_end(&UDPserverSoap);
}
soap_done(&UDPserverSoap);
}