0

I'm creating a python script that listens on several ports (defined in the portslist) and when someone connects to any of these ports, a "hello" message will be sent to them. Currently, the code below creates sockets for all ports in the portlist but only sends message to communication on last port.

Thanks

servers = []
for port in portlist:
    datasocket = ("0.0.0.0", port)

    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.bind(datasocket)
    server.listen(5)

    servers.append(server)


while True:
ready_server = select.select(servers, [], [])


for s in ready_server:
        connection, address = server.accept()
        print str(address) + " has connected!\n"
        msg ="hello\n"
        connection.send(msg)
        connection.close()
1
  • for one, you have bad indentation under that while loop Commented Mar 26, 2014 at 1:36

1 Answer 1

1

When select.select returns, ready_server will be a list of lists like this:

[[<sockets ready to read from>], [], []]

So for s in ready_server will iterate over these lists, not over the sockets.

Also, server.accept() within that loop doesn't refer to any loop variable, but to the server from the previous loop.

Try this:

servers = []
for port in portlist:
    datasocket = ("0.0.0.0", port)

    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.bind(datasocket)
    server.listen(5)

    servers.append(server)


while True:
    # unpack the returned list
    ready_server, _, _ = select.select(servers, [], [])


    for s in ready_server:
        # use s.accept instead of server.accept
        connection, address = s.accept()
        print str(address) + " has connected!\n"
        msg ="hello\n"
        connection.send(msg)
        connection.close()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.