I am using Visual Studio 6.0 VC++ on Windows XP (YES I know its old technology) I have a device which communicates via UDP all documentation says multicast and I wrote an app years ago that talks to it and uses multicast. my send and receive code will be below. My send works fine, using Wireshark I can see the message go out properly formatted and see the device respond with a properly formatted message. I CANNOT receive it into my code. It just sets there and listens infinitely, never receives anything. Here is what Wireshark displays coming back from the device:
Source 192.168.200.41 source port is 6311 (the device) Destination 192.168.200.72 destination port is 6303 (my development PC)
////////////////////////////Sender //////////////////////////////////
//
// create a send udp socket descriptor
//
SOCKET sUDPsocket = socket(AF_INET, SOCK_DGRAM, 0);
//
//initialize address struct
//
memset(&address_send, 0, sizeof(address_send));
address_send.sin_family = AF_INET;
address_send.sin_port = htons(localPort);
address_send.sin_addr.s_addr = inet_addr("239.255.255.250")
//
// send the contents of cBuffer
//
nBytesSent = sendto(sUDPsocket, cBuffer, nBufSize, 0,(SOCKADDR *) &address_send,sizeof(SOCKADDR_IN));
/////////////////////////// receiver /////////////////////////////////////////
//
// create a receive udp socket descriptor
//
SOCKET rUDPsocket = socket(AF_INET, SOCK_DGRAM, 0);
/
// initialize bind address struct
//
memset(&address_recv, 0, sizeof(address_recv));
address_recv.sin_family = AF_INET;
address_recv.sin_port = htons(6311);
address_recv.sin_addr.s_addr = htonl(INADDR_ANY);
//
// bind to this address/port
//
result = bind(rUDPsocket, (struct sockaddr*)&address_recv,
sizeof(address_recv));
//
// initialize recvfrom address struct
//
sockaddr sender_address;
rAddrsize = sizeof(sockaddr);
//
// receive data
//
rBytesRecv = recvfrom(rUDPsocket, rBuffer, rBufSize, 0,
(SOCKADDR *) &sender_address,
&rAddrsize);
/////////////////////////////////////////////////////////////////////////////
Your receiver isn't set up to receive multicast traffic. You need to use the IP_ADD_MEMBERSHIP
socket option to join a multicast group:
struct ip_mreq mreq;
mreq.imr_multiaddr = inet_addr("239.255.255.250");
mreq.imr_interface = inet_addr("192.168.200.72");
if (setsockopt(rUDPsocket, IPPROTO_IP, IP_ADD_MEMBERSHIP,
(char *)&mreq, sizeof(mreq)) == -1) {
char errbuf[300];
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, WSAGetLastError(),
0, errbuf, sizeof(errbuf), NULL);
fprintf(stderr, "(%d) %s", WSAGetLastError(), errbuf);
}
Also, make sure you're listening on the correct port. If the multicast packets have a destination port of 6311 you're fine. If not, change it to whatever that port is.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.