views:

507

answers:

1

I got multiple processes listening on the same port subscribed to a multicast address. Packets to this address reach every process. However, when I contact them via unicast, only the newest process gets the message. Where is this behavior documented? How can I change it?

Demo program (Python):

import socket,os,struct,sys

def server():
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind(('', 4242))

    mreq = '\xef\x01\x02\x03' + struct.pack('=I', socket.INADDR_ANY)
    sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

    while True:
     d = sock.recvfrom(1024)
     print('[s' + str(os.getpid()) + '] ' + repr(d))

def client():
    caddr = '239.1.2.3'
    caddr = '127.0.0.1' # Uncomment this and all servers print
    csock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    csock.sendto('data from ' + str(os.getpid()), 0, (caddr, 4242))

def main():
    if sys.argv[1] == 's':
     server()
    else:
     client()

if __name__ == '__main__':
    main()
+2  A: 

The MSDN states that the behaviour where multiple sockets are listening to the same port for unicast messages is undefined and that there's no way to know which one will receive the data. I tested a similar setup using C++ and winsock2.2 and had similar results as when I ran your program under python (namely the process-blocking effect).

Here's the MSDN article

GRB