在使用多个NIC的C ++中侦听多播时出现问题

时间:2011-02-27 10:20:24

标签: networking c++ multicast

我正在尝试在具有两个NIC的计算机上编写多播客户端,但我无法使其正常工作。我可以看到一个嗅探器,一旦我启动程序,NIC(eth4)开始接收多播数据报,但是,我无法接收()任何在我的程序中。

运行“tshark -i eth4 -R udp.port == xxx(组播端口)”时
我明白了:
1059.435483 y.y.y.y. (一些ip) - > z.z.z.z(multicast ip,not my eth4 NIC IP)UDP源端口:kkk(其他一些端口)目的端口:xxx(组播端口)

在网上搜索了一些示例/解释,但似乎我做了其他人所做的事情。任何帮助将不胜感激。 (与route / iptables / code有什么关系?)

bool connectionManager::sendMulticastJoinRequest()
{
struct sockaddr_in localSock;
struct ip_mreqn group;

char* mc_addr_str = SystemManager::Instance()->getTCP_IP_CHT();
char* local_addr_str = SystemManager::Instance()->getlocal_IP_TOLA();
int port = SystemManager::Instance()->getTCP_Port_CHT();
/* Create a datagram socket on which to receive. */

CHT_UDP_Feed_sock = socket(AF_INET, SOCK_DGRAM, 0);

if(CHT_UDP_Feed_sock < 0)
{
    perror("Opening datagram socket error");
    return false;
}
/* application to receive copies of the multicast datagrams. */
{
  int reuse = 1;
  if(setsockopt(CHT_UDP_Feed_sock, SOL_SOCKET, SO_REUSEADDR, (char *)&reuse, sizeof(reuse)) < 0)
  {
      perror("Setting SO_REUSEADDR error");
      close(CHT_UDP_Feed_sock);
      return false;
  }
}

/* Bind to the proper port number with the IP address */
/* specified as INADDR_ANY. */
memset((char *) &localSock, 0, sizeof(localSock));
localSock.sin_family = AF_INET;
localSock.sin_port = htons(port);
localSock.sin_addr.s_addr =inet_addr(local_addr_str); // htonl(INADDR_ANY); //
if(bind(CHT_UDP_Feed_sock, (struct sockaddr*)&localSock, sizeof(localSock)))
{
    perror("Binding datagram socket error");
    close(CHT_UDP_Feed_sock);
    return false;
}

/* Join the multicast group mc_addr_str on the local local_addr_str */
/* interface. Note that this IP_ADD_MEMBERSHIP option must be */
/* called for each local interface over which the multicast */
/* datagrams are to be received. */

group.imr_ifindex = if_nametoindex("eth4");
if (setsockopt(CHT_UDP_Feed_sock, SOL_SOCKET, SO_BINDTODEVICE, "eth4", 5) < 0)
    return false;
group.imr_multiaddr.s_addr = inet_addr(mc_addr_str);
group.imr_address.s_addr = htonl(INADDR_ANY); //also tried inet_addr(local_addr_str); instead
if(setsockopt(CHT_UDP_Feed_sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *)&group, sizeof(group)) < 0)
{
    perror("Adding multicast group error");
    close(CHT_UDP_Feed_sock);
    return false;
}

// Read from the socket.
char databuf[1024];
int datalen = sizeof(databuf);
if(read(CHT_UDP_Feed_sock, databuf, datalen) < 0)
{
    perror("Reading datagram message error");
    close(CHT_UDP_Feed_sock);
    return false;
}
else
{
    printf("Reading datagram message...OK.\n");
    printf("The message from multicast server is: \"%s\"\n", databuf);
}
return true;
}   

2 个答案:

答案 0 :(得分:1)

只是一个想法,(我没有做过很多关于多播的工作),但可能是因为你绑定到一个特定的IP地址?套接字可能只接受发往其绑定IP地址的数据包并拒绝多播数据包?

答案 1 :(得分:0)

好吧,不久之前我没有玩多播。您是否需要root / admin权限才能使用它?启动程序时是否启用了它们?