2

Im new in Python. And I can't make the server listen to two ports at the same time. This is the code I have written until now:

sock_client1 = socket.socket(socket.AF_INET,    # Internet
                     socket.SOCK_DGRAM)         # UDP
sock_client1.bind((SEND_IP, SEND_CLIENT_PORT))
sock_client1.setblocking(0)     

sock_client2 = socket.socket(socket.AF_INET,    # Internet
                     socket.SOCK_DGRAM)         # UDP
sock_client2.bind((SEND_IP, SEND_SERVER_PORT))
sock_client2.setblocking(0)             

while True:
try:

    ready_client1 = select.select([sock_client1], [], [], None)
    ready_client2 = select.select([sock_client2], [], [], None)

    if ready_client1[0]:

        pkt_recv_raw, addr = sock_client1.recvfrom(4096)
        port = SEND_CLIENT_PORT

    if ready_client2[0]:

       pkt_recv_raw, addr = sock_client2.recvfrom(4096)
       port = SEND_SERVER_PORT

When I run this code together with a client, the server can't receive anything. It just works when I use only one of the ready_client's.

Thanks in advance!

user00
  • 45
  • 6
  • why should the same code listen on both the client socket and the server socket? – e4c5 Jul 05 '16 at 04:31
  • @e4c5 Sorry, I'm not sure I understood your question. Maybe this will help: this code is actually a module that should work transparently for the transmission between two nodes. It receives their packets and retransmits them to the real destination node. I need to know from who I have received so then I can know to whom I should send the data. Since I'm simulating it locally, the port number is the way I'm using to distinguish the sources. – user00 Jul 05 '16 at 04:39
  • In that case it sounds like you are trying to reinvent iptables or similar. – e4c5 Jul 05 '16 at 04:41
  • @e4c5 Well, I'm just trying to solve the problem. This is my first time with python. Do you know what am I doing wrong? – user00 Jul 05 '16 at 04:46
  • yes. using python. use iptables – e4c5 Jul 05 '16 at 07:22

1 Answers1

4
ready_client1 = select.select([sock_client1], [], [], None)
ready_client2 = select.select([sock_client2], [], [], None)

Try using a single select:

ready_read, ready_write, exceptional = select.select(
    [sock_client1, sock_client2], [], [], None)


for ready in ready_read:
    pkt_recv_raw, addr = ready.recvfrom(4096)
...
cnicutar
  • 178,505
  • 25
  • 365
  • 392