Problem receiving UDP broadcast packets.

Heiko Wundram modelnine at
Wed Apr 20 16:53:53 CEST 2011

Am 20.04.2011 16:30, schrieb Grant Edwards:
>> If you need to see the packets regardless, either use a promiscuous mode
>> sniffer (i.e., tcpdump, but that's relatively easy to mirror in Python
>> using SOCK_RAW, capturing packets at the ethernet level), or add a route
>> on your system for the 192.168.x.x network on the same interface.
> I've thought about the SOCK_RAW option, but the CPU load of looking
> all received Ethernet packets in user-space would be a big down-side.

Not necessarily: instead of using UDP datagrams to send the data, use
ethernet datagrams (without any IP/UDP header) with your own
ethernet-type (there is a range of "local" types that you can use for
your own local use-case), and then simply create a RAW socket that only
listens on packets that have the specified ethernet types. We use
something similar at work for a high-availability application.

The server-side looks something like:

PKT_TYPE = 0x1234 # My very own ethertype.

sock = socket(AF_PACKET,SOCK_DGRAM,htons(PKT_TYPE))

while True:
    data, (_, _, _, _, addr) = sock.recvfrom(1500)
    print "I got:", repr(data), "from etheraddr:", addr

The client-side looks similar.

Because you're using UDP broacast, you have unreliable transport anyway,
and if the client-side supports sending ethernet datagrams (with a
broadcast address), I'd rather advise to use that for your use case.
This makes you independent of IP configuration (and as I can see, you're
actually not interested in the "routing" that IP gives you, but rather
interested in contacting all nodes on a local ethernet; why not use
ethernet directly?).

--- Heiko.

More information about the Python-list mailing list