I'm trying to receive multicast UDP packets in Python. The packets are visible in Wireshark but are not being received by my Python program. The multicast group is 224.0.2.2, and the port is 42102. The packets are being sent to this group and port, and I can confirm their arrival with Wireshark. However, my Python script, which is supposed to receive these packets, does not receive them.
Below is my Python code:
import socket
import struct
MCAST_GRP = '224.0.2.2'
MCAST_PORT = 42102
INTERFACE = 'eno2'
# Creating a socket
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
print("Socket created successfully.")
except socket.error as err:
print(f"Failed to create socket. Error: {err}")
# Socket options for reuse address
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# Binding to a specific interface
try:
sock.setsockopt(socket.SOL_SOCKET, 25, str(INTERFACE + '\0').encode('utf-8'))
print(f"Socket bound to interface {INTERFACE}.")
except socket.error as err:
print(f"Failed to bind socket to interface. Error: {err}")
# Binding the socket to the multicast group and port
try:
sock.bind(('', MCAST_PORT))
print(f"Socket bound to port {MCAST_PORT}.")
except socket.error as err:
print(f"Failed to bind socket to port. Error: {err}")
# Joining the multicast group
try:
mreq = struct.pack("4sl", socket.inet_aton(MCAST_GRP), socket.INADDR_ANY)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
print(f"Joined multicast group {MCAST_GRP}.")
except socket.error as err:
print(f"Failed to join multicast group. Error: {err}")
# Receiving data
try:
while True:
print("Waiting for data...")
data, addr = sock.recvfrom(10240)
print(f"Data received from {addr}: {data.decode('utf-8')}")
except socket.error as err:
print(f"Error receiving data. Error: {err}")
except KeyboardInterrupt:
print("\nExiting.")```
The output I get is:
Socket created successfully.
Socket bound to interface eno2.
Socket bound to port 42102.
Joined multicast group 224.0.2.2.
Waiting for data...
However, in Wireshark, I can clearly see the packets arriving on interface eno2, destined for 224.0.2.2:42102, with the following output:
3133 4.569466995 10.13.1.113 → 224.0.2.2 UDP 130 42402 → 42102 Len=84
Any ideas why my Python code is not receiving the packets, while Wireshark can see them? Are there any socket options or settings I'm missing, or is there something else I need to consider?
224.0.2.2instead of0.0.0.0.mreq = struct.pack("4s4s", socket.inet_aton(MCAST_GRP), socket.inet_aton(224.0.2.2))?sock.bind(('224.0.2.2', MCAST_PORT))bind(). Surely this is obvious?