简体   繁体   中英

How do I make a server listen on multiple ports

I would like to listen on 100 different TCP port with the same server. Here's what I'm currently doing:-

import socket
import select

def main():

    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    for i in range(1000,1100):
        server_socket.bind(('127.0.0.1', i))
    server_socket.listen(1)

    read_list = [server_socket]
    while True:
        readable, writable, exceptional = select.select(read_list, [], read_list)
        for s in readable:
            if s is server_socket:
                #print "client connected"
                client_socket, address = server_socket.accept()
                read_list.append(client_socket)
            else:
                # One of the tcp clients
                data = s.recv(1024)
                if not result:
                    s.close()
                    read_list.remove(s)
                    #print "client disconnected"

if __name__ == "__main__":
    main()

It returns an error saying Permission Denied . Is it because some ports(1000-1100) are reserved and are not allocated to it or because of some other reason?

I tried with (8000-8100) and it says Invalid Arguments

EDITED

import socket
import select

def create_socket(TCP_PORT):
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server_socket.bind(('127.0.0.1', TCP_PORT))
    server_socket.listen(1)

    return server_socket


def main():

    read_list = []

    for TCP_PORT in range(8000,8100):
        read_list.append(create_socket(TCP_PORT))

    while True:
        readable, writable, exceptional = select.select(read_list, [], read_list)
        for s in readable:
            if s is server_socket:
                #print "client connected"
                client_socket, address = server_socket.accept()
                read_list.append(client_socket)
            else:
                # One of the tcp clients
                data = s.recv(1024)
                if not result:
                    s.close()
                    read_list.remove(s)
                    #print "client disconnected"

if __name__ == "__main__":
    main()

There are 2 problems.

  1. Ports below 1024 are reserved. (You'll need special privileges, eg root privileges to bind to such a port).

  2. A socket can only listen at one port. So to listen to several port, you need to create one socket per port.

You will find a nice explaination here : Listen to multiple ports from one server . It is for C but the problem in python is the same.

So the answer will be the same :

  • one socket per port
  • one listen per socket
  • a single select

By the way ports below 1024 ar reserved on Unix (and Unix-like) systems : you need root privileges to use them. On Windows, there are no such restrictions.

Regarding the second problem - using ports 8000-8100 causes Invalid argument , this occurs if you try to rebind an already bound socket without first recreating the socket. There is no problem with that port range however.

>>> s=socket.socket()
>>> s.bind(('localhost', 8001))
>>> s.bind(('localhost', 8001))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.7/socket.py", line 224, in meth
    return getattr(self._sock,name)(*args)
socket.error: [Errno 22] Invalid argument
>>> s.close()
>>> s.bind(('localhost', 8001))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.7/socket.py", line 224, in meth
    return getattr(self._sock,name)(*args)
  File "/usr/lib64/python2.7/socket.py", line 170, in _dummy
    raise error(EBADF, 'Bad file descriptor')
socket.error: [Errno 9] Bad file descriptor
>>> s=socket.socket()
>>> s.bind(('localhost', 8001))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM