5

I'm trying to receive a multicast data from specific network interface on CentOS 5.5

sd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(1234);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
bind(sd, (sockaddr*)&addr, sizeof(sockaddr_in));
setsockopt(sd, SOL_SOCKET, SO_BINDTODEVICE, "eth0", 5);

But I'm receiving packets from all interfaces.

What wrong?

Kara
  • 6,115
  • 16
  • 50
  • 57
Dima
  • 1,253
  • 3
  • 21
  • 31
  • Shouldn't that be `setsockopt(sd, SOL_SOCKET, SO_BINDTODEVICE, "eth0", 4);`? (notice the 4 vs 5). – Thomas M. DuBuisson Sep 24 '10 at 21:43
  • I tried setsockopt(sd, SOL_SOCKET, SO_BINDTODEVICE, "eth0", 4), but the setsockopt() is failed. I think (not sure) that 5 is including termination zero. – Dima Sep 24 '10 at 21:45

1 Answers1

6

First, check if any of your calls fail, socket,bind,setsockopt in this case. Printing an error message with the perror() function will help you diagnose problems.

However, for receiving multicast datagrams you might need to specify the ip address of the interface when you join a multicast group using the IP_ADD_MEMBERSHIP socket option Something like

  setsockopt (sd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq));

where the mreq struct is

struct ip_mreq
{
        struct in_addr imr_multiaddr;   /* IP multicast address of group */
        struct in_addr imr_interface;   /* local IP address of interface */
};

More info here.

nos
  • 223,662
  • 58
  • 417
  • 506
  • I changed ADD_MEMBERSHIP according to you. The result is same: I'm still receiving multicasts from other interfaces. BTW, in my real code I'm checking return values of all APIs. Thanks, Dima – Dima Sep 24 '10 at 22:26