Results 1 to 3 of 3
Hi all,
I am trying to setup a socket that listens and send on a specific NIC. This socket also joins a multicast group. For some reason it doesn't work. ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
- 07-14-2010 #1Just Joined!
- Join Date
- May 2010
- Posts
- 9
Multicast on a specific NIC
Hi all,
I am trying to setup a socket that listens and send on a specific NIC. This socket also joins a multicast group. For some reason it doesn't work. Here is a sample code of what I do:
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define MY_IP "20.1.1.1"
#define MY_PORT 52101
#define MY_MC "230.0.0.8"
int main()
{
int sock = socket (AF_INET, SOCK_DGRAM, 0);
if (sock <= 0)
return -1;
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr (MY_IP);
addr.sin_port = htons (MY_PORT);
int ret = bind (sock, (sockaddr*)&addr, sizeof (addr));
if (ret != 0)
return -1;
ip_mreq mreq;
mreq.imr_multiaddr.s_addr = inet_addr (MY_MC);
mreq.imr_interface.s_addr = inet_addr (MY_IP);
ret = setsockopt (sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof (mreq));
if (ret != 0)
return -1;
char buff[1500];
ret = recv (sock, buff, sizeof (buff), 0);
if (ret <= 0)
{
printf ("Error in recv!\n");
return -1;
}
printf ("Received packet from MC!!");
return 0;
}
In this sample the recv function never returns. If I change MY_IP to be INADDR_ANY the function recv returns. In my application I want to get only packets from a specific interface and not from all of them.
Thx in advance for help.
- 07-14-2010 #2Just Joined!
- Join Date
- Jul 2010
- Posts
- 53
instead of:
mreq.imr_interface.s_addr = inet_addr (MY_IP);
i think you want:
mreq.imr_interface.s_addr=htonl(INADDR_ANY);
if that's not the issue then i can look more closely...
- 07-16-2010 #3Just Joined!
- Join Date
- May 2010
- Posts
- 9
Hi,
Thank you for answering.
What I meant was that if I replace the line:
addr.sin_addr.s_addr = inet_addr (MY_IP);
with
addr.sin_addr.s_addr = htonl (INADDR_ANY);
then it works fine and my socket receives multicast packets. The problem is that in this case I also receive non-multicast packets with destination port=MY_PORT which arrived on other interfaces.


Reply With Quote
