Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a server listen on multiple ports

Tags:

python

sockets

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()
like image 446
PythonEnthusiast Avatar asked Aug 05 '14 09:08

PythonEnthusiast


1 Answers

There are 2 problems.

  1. Ports below 1024 are reserved. (You'll need special privileges, e.g. 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.

like image 188
nos Avatar answered Oct 17 '22 01:10

nos