Search code examples
pythonubuntuudpbroadcast

Can't receive UDP broadcast with python on Ubuntu 20.04 LTS, works on Raspbian & Centos on same network


I've got a device on my LAN that is sending broadcast packets on UDP 50222. Using tcpdump, I can see the packets, but in python on my Ubuntu 20.04 LTS box no data is received. However, on 2 other systems on the same LAN (Centos 7.8 and Raspbian 9 [stretch]) the exact same code works. This doesn't seem to be entirely limit to python; running nc -lu 50222 on the two non-Ubuntu systems works, but no data is received on the Ubuntu box.

Here's some code I've used to test this:

import socket

client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) # UDP
client.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
client.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
client.bind(("", 50222))
while True:
    data, addr = client.recvfrom(1024)
    print("received message: %s"%data)

I believe the two calls to setsockopt() aren't actually needed, but I've tried both with and without them and it makes no difference on any of the machines.

I've tried running both the sample code as well as netcat under sudo but that makes no difference. Looking at the tcpdump captures in Wireshark, the packets contain the data I expect, and the checksums are correct.

Searching here and elsewhere, the most common issue I've seen is not doing the bind correctly, but I believe that what I've used is correct.

Any suggestions?


Solution

  • It turned out that there was a firewall enabled on the Ubuntu box that was locked down to the point where local traffic was only allowed on specific ports. Adding a rule to allow that fixed the problem. I'm still not quite sure why tcpdump worked, presumably it's at a lower layer and isn't subject to the firewall.