psuedo TCP multicast with os.dup2() in python?

249 views Asked by At

The idea is to multicast the same content from one single resource to multiple receivers at once. I came up with the following code:

#!/usr/bin/env python
# coding: utf8

import socket, os

c = socket.socket()
c.connect(('127.1', 4343))

s = socket.socket()
s.bind(('127.1', 8989))
s.listen(3)
while 1:
  conn, addr = s.accept()
  print 'Connected by %s:%s' % addr
  os.dup2(conn.fileno(), c.fileno(), )
s.close()

I tested it with netcat without any success, either the client quits unexpected or the server exits after anything connects. Is this possible at all? What did I do wrong?

1

There are 1 answers

0
PlushBeaver On BEST ANSWER

After os.dup2() call both file descriptors (FDs) refer to the same socket, thus sharing its buffers. When data is extracted (via recv() or read()) using original FD, this fragment can no longer be extracted using duplicated FD, and vice versa. Each octet of incoming data will be read exactly once and by a single receiver, it won't be duplicated for each FD (that's where you are mistaken, I suppose).

For reliable multicast solutions see this answer and the linked topic.