3

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))
Community
  • 1
  • 1
azhurb
  • 43
  • 2
  • 8
  • Well, apparently there used to be a problem where the `socket` module wasn't thread-safe (http://bugs.python.org/issue1544279), but that's been fixed since Python 2.5 or so, it seems. – JAB Jun 17 '11 at 14:58
  • Today I tried to run this script on python3 - the result is the same. – azhurb Jun 20 '11 at 09:32
  • Wait... What effect does binding a socket to an empty host and then assigning the host later have? – JAB Jun 20 '11 at 13:26
  • I thought it was a feature of the multicast. This code is found in many examples. But today I tried binding a socket to an multicast group and it looks like it works, the problem disappeared. – azhurb Jun 20 '11 at 21:21
  • Heh, I had a feeling it'd be something like that. – JAB Jun 20 '11 at 21:28
  • I post a possible [anwer](http://stackoverflow.com/a/33044795/3102264) without binding socket to multicast group to a duplicate [post](http://stackoverflow.com/questions/29833542/why-are-multicast-messages-on-the-same-port-but-from-different-groups-combined) – mpromonet Oct 21 '15 at 05:52

1 Answers1

3

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.

phihag
  • 278,196
  • 72
  • 453
  • 469
  • Yes, it seems azhurb figured that out today. – JAB Jun 20 '11 at 21:30
  • @JAB I know, that's why this answer is marked community wiki. It helps to keep the structured question-answer format, and if something can be written better, it's way better to edit a community wiki answer than to append another comment. – phihag Jun 20 '11 at 21:34