Duplicate packets in Python multicast receiver

2019-02-25 08:56发布

问题:

There is a script that opens a socket and read from it the multicast (from Multicast in Python)

import socket
import struct

MCAST_GRP = '224.1.1.1'
MCAST_PORT = 1234

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('', MCAST_PORT))
mreq = struct.pack("4sl", socket.inet_aton(MCAST_GRP), socket.INADDR_ANY)

sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

while True:
  print sock.recv(10240)

Everything is fine as long as I do not run parallel to the same script to another multicast group, but the ports are the same, for example

rtp://224.1.1.1:1234
rtp://224.1.1.2:1234

After starting the second script starts mess - the first script sees packets for the second and the second to first.

I tried to do as a mcast.py - a similar result.

Why is this happening and how to cure?

UPD Fix

-sock.bind(('', MCAST_PORT))
+sock.bind((MCAST_GRP, MCAST_PORT))

回答1:

An application listening to all incoming connections on a port will get all messages to that port, no matter which application initiated multicast group membership. To mitigate this, have every application listen to the multicast address it's expecting data from, by specifying it as the first argument in the address tupel given to bind.