mercredi 13 janvier 2021

Receiving Unicast and Multicast on the Same Socket in C++

I need to receive both unicast and multicast UDP on the same socket and port at a specific IP. Based on other questions asked here, this should be possible. I can set all the options and bind successfully, but I cannot receive any traffic. It just stays blocked at read() call.

I have tried many different options, such as SO_BROADCAST, SO_REUSEADDR, and SO_REUSEPORT. I have tried setting multicast group address to "0.0.0.0," but that fails. I just don't know how to properly do this.

Here is a stripped-down version of my current status:

struct sockaddr_in localSocket;
int sd = socket(AF_INET, SOCK_DGRAM, 0);
//error check here
int broadcast = 1;
if ((setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, (char*)&broadcast, sizeof(broadcast)) < 0 || 
(setsockopt(sd, SOL_SOCKET, SO_REUSEPORT, (char*)&broadcast, sizeof(broadcast)) < 0)) //I have tried either one of these options, as well as SO_BROADCAST. Now I am trying to use both
//error handling here
else 
{
memset((char*) &locakSocket, 0, sizeof(localSocket));
localSocket.sin_family = AF_INET;
localSocket.sin_port = htons(port);//port that I want to receive on
localSocket.sin_addr.s_addr = inet_addr(IP); //local IP that I want to receive on. I have tried "0.0.0.0" here as well, but I still do not receive anything
}
if(bind(sd,(struc sockaddr*)&kicakSicjetm suzeif(localSocket))<0)
//error handling
else
{
//trying to join multicast here:
struct ip_mreq group;
group.imr_multiaddr.s_addr = inet_addr("239.255.1.1");//IP address that the multicast is being sent from. I have tried "0.0.0.0" here too, but that fails.
group.imr_interface.s_addr = inet_addr(IP);//local IP that I want to receive on. I have tried skipping this line, but I still do not receive any traffic
}
if(setsockopt(sd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &group, sizeof(group)) < 0)
//error handling
else
{
while(!terminate)
{
numbytes = read(sd,packet,sizeof(packet));//this breakpoint is hit, but I never hit any line afterwards
}
}

Since I get to the final line, I know that none of the setsocketopt(), bind(), etc fail. I just don't ever read anything. Am I doing something out of order? It feels strange to setsockopt, bind, and then setsockopt again, but that is where my research lead me.

Aucun commentaire:

Enregistrer un commentaire