Reputation: 151
I have a sensor that sends udp packets on mulitcast group 224.0.2.2 to port 42102. It is connected to one of several network adapters in a computer, that has the address 10.13.1.100 assigned to it. The packets are visible as expected in Wireshark on the specified interface. The code I'm currently using:
import socket
import struct
# Create a UDP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Bind the socket to the port
server_address = ('224.0.2.2', 42102)
sock.bind(server_address)
# Tell the kernel that we want to join a multicast group
# The address for the multicast group is the third parameter
group = socket.inet_aton('224.0.2.2')
mreq = struct.pack('4sL', group, socket.INADDR_ANY)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# Set the interface to listen on
interface = socket.inet_aton('10.13.1.100')
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF, interface)
# Receive messages
while True:
data, address = sock.recvfrom(1024)
print('Received %s bytes from %s' % (len(data), address))
print(data)
This reaches the recvfrom
command and hangs, suggesting the socket is not receiving anything.
I suspect there is some configuration error.
Any help is appreciated
Upvotes: 1
Views: 2107
Reputation: 223699
By joining the multicast group on interface socket.INADDR_ANY
, you'll telling the OS to pick one interface to listen on, which may not be the one you want. You should set this to the specific interface IP.
group = socket.inet_aton('224.0.2.2')
interface = socket.inet_aton('10.13.1.100')
mreq = struct.pack('4sI', group, interface)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
Setting IP_MULTICAST_IF
does not specify which interface to listen on. It specifies which interface to send multicast traffic from.
Upvotes: 2