RYS
RYS

Reputation: 462

Subscribing to UDP multicast with Python

This topic has been covered in a good amount of detail here, unfortunately, I'm still running into some trouble.

I'm trying to subscribe to a stream of motion-capture data from a windows box on my network. The mo-cap server is broadcasting over my network, and I can pick up the data with wireshark on my OS X machine ('the target'). I see that a message originating from the origin ip 204.102.224.2 (windows) broadcasting on 239.255.42.99 via UDP, to port 1511 is going out, as desired.

My python code is as follows:

PORT = 1511
MULTICAST_ADDRESS = '239.255.42.99'
SOCKET_BUFSIZE = 1024

datasock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
datasock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
datasock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
datasock.bind((MULTICAST_ADDRESS, PORT))
mreq = struct.pack("=4sl", socket.inet_aton(MULTICAST_ADDRESS), socket.INADDR_ANY)
datasock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 32)
datasock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 1)
datasock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, SOCKET_BUFSIZE)
datasock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

while 1:
    data = datasock.recv(rx.MAX_PACKETSIZE)
    packet = rx.unpack(data, version=version)
    if type(packet) is rx.SenderData:
        version = packet.natnet_version
        #print("NatNet version received:", version)
    if type(packet) in [rx.SenderData, rx.ModelDefs, rx.FrameOfData]:
        packet_dict = packet._asdict()
        all_bodies = packet_dict['rigid_bodies']
        for body in all_bodies:
            contortion = body._asdict()['orientation']
            euler = Quat([elem for elem in contortion]).equatorial

I think for my current issue it is safe to ignore some of the code in the loop, as some of it derives from a helper library I'm using (optirx). Note that I didn't start out with all the options, but decided to include all of them to see what should stay and what can go. I've tried various combinations and permutations. I'm on OS X 10.10.3

Upvotes: 2

Views: 6609

Answers (1)

dbush
dbush

Reputation: 223699

The problem is here:

datasock.bind((MULTICAST_ADDRESS, PORT))

You shouldn't bind the socket to the multicast address. You should bind it to '0.0.0.0'. The setsockopt call with IP_ADD_MEMBERSHIP takes care of joining the multicast group.

Upvotes: 2

Related Questions