2

I am trying to create socket that can receive multicast UDP packages on my Ubuntu using Python 2.7.3. I have based my code on https://stackoverflow.com/a/1794373/1444854

Unfortunately I keep getting the same error:

   self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
File "/usr/lib/python2.7/socket.py", line 224, in meth
   return getattr(self._sock,name)(*args)
socket.error: [Errno 22] Invalid argument

This is the code I have used

self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.bind(("", 12345))
self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

Where for 'mreq' I have tried various stuff, of which I show a few here. For the format in the struct examples I have used both with and without the network byte order indicator ('!'). The native one seems to double the size (from 8 to 16). I have also tried both signed and unsigned longs ('l' and 'L').

group = "127.0.0.1" # Or any other ipv4 address...
mreq = socket.inet_aton(group) + socket.inet_aton("0.0.0.0")
mreq = struct.pack("4sL", socket.inet_aton(self.group), socket.inet_aton("0.0.0.0"))
mreq = struct.pack("4sL", socket.inet_aton(self.group), socket.htonl(socket.INADDR_ANY))
mreq = struct.pack("4sL", socket.inet_aton(self.group), socket.INADDR_ANY)

At this point I do not know what the problem is, and could use some help with this. I thought that the wrong 'mreq´ would provide an issue, but after so many tries I feel there must be something else I am missing.

Any help is appreciated. If more information is needed, I will gladly provide it.

EDIT:

The problem, which I totally overlooked, was the fact that I needed a proper multicast interface. Using 'ifconfig wlan0' or any other interface, you can check that MultiCast is in fact enabled. Furthermore I think any address between 224.3.* and 224.250.* has not been assigned for other uses. The 'mreq' that works for me is

    mreq = struct.pack("!4sl", socket.inet_aton(self.group), socket.INADDR_ANY)
Community
  • 1
  • 1
Vincent Ketelaars
  • 1,069
  • 1
  • 14
  • 35

1 Answers1

4

This thread is old but it might help to know that IPV4 Multicast addresses use reserved class D address range: 224.0.0.0 through 239.255.255.255

If IP address is out of this range, setsockopt will throw 'Invalid argument' error.

cheers