简体   繁体   English

UDP广播接收-绑定到多个NIC

[英]UDP Broadcast receive - Bind to several NIC's

I am writing a program for Linux that should receive UDP broadcast packets from the specified port on any of the network interfaces that exist in the system. 我正在为Linux编写一个程序,该程序应该从系统中存在的任何网络接口上的指定端口接收UDP广播数据包。

However, if the system has multiple network interfaces of the same subnet address, the packets are accepted only by the first interface. 但是,如果系统具有相同子网地址的多个网络接口,则仅第一个接口接受数据包。

For example, if eth0 has 192.168.225.107 and eth1 has 192.168.225.108, packets accepted only from eth0. 例如,如果eth0具有192.168.225.107,而eth1具有192.168.225.108,则仅从eth0接受数据包。

NIC's are attached to different physical networks. NIC连接到不同的物理网络。 According to the tcpdump, the packets are present in both networks. 根据tcpdump,两个网络中都存在数据包。

Code (error checking skipped): 代码(跳过错误检查):

sock = socket(PF_INET, SOCK_DGRAM, 0);
setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (void *) &on, sizeof(on));
setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (void *) &s, sizeof(s));
bzero(&serv_addr_ip, sizeof(serv_addr_ip));
serv_addr_ip.sin_family = AF_INET;
serv_addr_ip.sin_port = htons(port);
serv_addr_ip.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr = (struct sockaddr *) &serv_addr_ip;
addr_len = sizeof(struct sockaddr_in);
bind(sock, serv_addr, addr_len);

while (1) {
    if ((chars = recvfrom(sock, var.buf, MSG_MAX, 0, serv_addr, &addr_len)) < 0) {
        ...
    }
...
}

If I understand you correctly, you have two NICs, connected to two physical networks (ie network cables, hubs), with each having a separate IP address from the same subnet address range? 如果我理解正确,那么您有两个NIC,分别连接到两个物理网络(例如,网络电缆,集线器),并且每个NIC都具有来自同一子网地址范围的单独IP地址?

The short answer is that your network configuration is wrong. 简短的答案是您的网络配置错误。 If they really are separate physical networks, then they should have different subnet addresses. 如果它们确实是单独的物理网络,则它们应具有不同的子网地址。 It depends on what you mean with separate physical networks, separate hardware? 这取决于您对单独的物理网络,单独的硬件的含义? You can NOT have two separate subnets with the same subnet address. 您不能有两个具有相同子网地址的单独子网。 Thats why I am saying your network configuration is wrong. 那就是为什么我说您的网络配置错误。

However, The impression I get is that you are trying to bridge the two networks, so that the two NICs belong to the same subnet (not separate). 但是,我得到的印象是您正在尝试桥接两个网络,以使两个NIC属于同一子网(不是分开的)。 Well, then you should bridge them. 好吧,那么您应该桥接它们。 You bridge the two NICs together and assign ONE IP address to the bridge. 您将两个NIC桥接在一起,并为桥接分配一个IP地址。 Then you will be able to receive your packets on both NICs. 然后,您将能够在两个NIC上接收数据包。

In linux: 在Linux中:

brctl addbr br0
ifconfig eth0 0.0.0.0 down
ifconfig eth1 0.0.0.0 down
brctl addif br0 eth0
brctl addif br0 eth1
ifconfig eth0 up
ifconfig eth1 up
ifconfig br0 up
ifconfig br0 192.168.225.107 (or 192.168.225.108, whatever you prefer)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM