0
votes

I have been looking at previous questions but so far, none of them has helped solved my issue.

I am trying to receive data from a simulator, do some decoding and encoding, before sending it out to another receiver on the other end.

Currently using UDP multicast, my receiver function works fine, and part of the code is:

int multicast = 1;

SOCKET recvsock;
sockaddr_in recvaddr;
struct ip_mreq mreq;

memset(&recvaddr, 0, sizeof(recvaddr);
memset(&mreq, 0, sizeof(mreq);

recvaddr.sin_family = AF_INET;
recvaddr.sin_addr = htonl(INADDR_ANY);
recvaddr.sin_port = htons(8807);

mreq.imr_interface.s_addr = INADDR_ANY;
mreq.imr_multiaddr.s_addr = inet_addr("239.254.4.27");

setsockopt(recvsock, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char*)&mreq, sizeof(mreq));
setsockopt(recvsock, SOL_SOCKET, SO_REUSEADDR, (char*)&multicast, sizeof(multicast));

bind(recvsock, (SOCKADDR*)&recvaddr, sizeof(recvaddr));

The above socket settings and socket options works for receiving. I have removed the checks for SOCKET_ERROR to reduce the length in my question, I have it in my current code for checking purposes.

As from my understanding, the concept of udp multicast, is for the client or server to join the udp multicast group to send or receive data, and the IP used 239.254.4.27 to the group to join, hence this mreq.imr_multiaddr.s_addr = inet_addr("239.254.4.27").

I have to use SO_REUSEADDR because I have to bind the same port number multiple times, I believe the simulator is binding the port as well, as I have faced error 10048 if I do not use it.

However, when I did the same thing for the sending function, code below:

SOCKET sendsock;
sockaddr_in sendaddr;

memset(&rsendaddr, 0, sizeof(sendaddr);
memset(&mreq, 0, sizeof(mreq);

sendaddr.sin_family = AF_INET;
sendaddr.sin_addr = htonl(INADDR_ANY);
sendaddr.sin_port = htons(8807);

mreq.imr_interface.s_addr = INADDR_ANY;
mreq.imr_multiaddr.s_addr = inet_addr("239.254.4.27");

setsockopt(sendaddr, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char*)&mreq, sizeof(mreq));
setsockopt(sendaddr, IOL_SOCKET, SO_REUSEADDR, (char*)&multicast, sizeof(multicast));

bind(sendaddr, (SOCKADDR*)&sendaddr, sizeof(sendaddr));

The bind returns successful, however when i do this:

int send_data = sendto (sendsock, stringdata.c_str(), sizeof(stringdata), 0,(struct sockaddr*)&sendaddr, sizeof(sendaddr));

I have an error of 10049, which is WSAEADDRNOTAVAIL, which means Cannot assign requested address.

EDIT: I am currently using the Microsoft loopback adapter, do I have to include the loopback adapter's IP as well.

Am i having a misunderstanding somewhere, or there is something wrong with my code, please advise.

1

1 Answers

0
votes
  • INADDR_ANY is not a target IP address, nor is it the multicast group address, which is what you should be sending to.
  • You don't need to join the group to send to it.
  • sendaddr should be sendsock in several places in your code.
  • sizeof stringdata does not yield the length of the string it contains.