5

I found multiple answers that suggest using the SO_REUSEPORT socket option when multiple UDP clients need to listen for broadcasts on the same port. However I'm getting an error that this option is not available. Using python 2.7

from socket import *
s = socket(AF_INET, SOCK_DGRAM)
s.setsockopt(SOL_SOCKET, SO_REUSEPORT, 1)
try:
    s.bind(('', MYPORT))
except:
    print "Error connecting to the UDP stream."


Traceback (most recent call last):
  File "qsorder.py", line 119, in <module>
    s.setsockopt(SOL_SOCKET, SO_REUSEPORT, 1)
NameError: name 'SO_REUSEPORT' is not defined

I've tried SO_REUSEADDR and it does not give an error but only one client receives broadcasts. Any idea how to work around this?

k3it
  • 1,621
  • 3
  • 15
  • 18
  • What do you call "broadcast"? What address are datagrams sent to? – Nikolai Fetissov Nov 30 '12 at 02:54
  • the udp packets are sent to the broadcast address for the subnet (255 in the last octet). I'm trying to run multiple instances of the script on the same PC and each listen to these broadcasts without exclusively locking up the port to which the datagrams are sent. – k3it Nov 30 '12 at 03:23
  • With `255.255.255.0` network mask? – Nikolai Fetissov Nov 30 '12 at 03:39
  • yes /24 mask. does it really make a difference if they are broadcast or unicast, at least in this specific case? ;) – k3it Nov 30 '12 at 03:55

1 Answers1

3

You need to set SO_BROADCAST option on each socket:

s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)

SO_REUSEPORT is not standard and usually means same thing as SO_REUSEADDR where supported.

Nikolai Fetissov
  • 77,392
  • 11
  • 105
  • 164
  • that flag didn't work by itself, however with both SO_BROADCAST and SO_REUSEADDR set it looks better and multiple instances are receiving the packets! – k3it Nov 30 '12 at 04:41
  • Yes, that's what I meant - you need both. And oops, didn't see the obvious omission of `SO_BROADCAST` in your original code. – Nikolai Fetissov Nov 30 '12 at 04:50
  • 1
    more on that here: http://stackoverflow.com/questions/14388706/socket-options-so-reuseaddr-and-so-reuseport-how-do-they-differ-do-they-mean-t?rq=1 – bubakazouba May 31 '15 at 01:01