I wish to know is there any way I can disable the UDP broadcast packet from the node A to not received by node A itself.
For braodcast I am simply using INADDR_BROADCAST
and o开发者_运维技巧n the
receiver side I am using AI_PASSIVE | AI_NUMERICHOST
.
No, this is fundamental property of broadcasting - every host on the subnet, including the sender, will have to process the packet all the way up the network stack. You options are:
- Switch to multicast. This is preferred since multicast reduces the load on the whole network compared to broadcast, and because you can explicitly control multicast loopback with the
IP_MULTICAST_LOOP
socket option. - Don't
bind(2)
the destination port on the sending machine. This works but is sort of kludgy since it puts restrictions on application design and/or deployment.
Bind to interface, not just address.
#include <net/if.h>
#include <socket.h>
struct ifreq interface;
strcpy(interface.ifr_ifrn.ifrn_name, "eth0");
int fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, &interface, sizeof(interface));
//... bind(fd,...) ...
This way data that didn't arrive at the interface specified (but originated from it instead) will not be received.
Here are results of my experiments with Python's socket library. Whether UDP broadcaster receives messages sent by itself is dependent on what address will you bind broadcasting socket to. For greater clarity, broadcaster's IP address was 192.168.2.1.
- When binding to '192.168.2.255' or '' (empty address), broadcaster receives messages sent by itself
- When binding to '192.168.2.1', '255.255.255.255' or '<broadcast>', broadcaster will NOT receive messages sent by itself
Receiver received broadcasted UDP messages in all these cases.
P.S. Tested on Python 2.7.9, OS Raspbian 8 (adaptation of Debian for Raspberry Pi), Linux kernel 4.4.38
精彩评论