a2mky
a2mky

Reputation: 193

Python socket listen on all ports

Basically, I want to listen to all ports using the socket module. How do I make it so that port is = to all the open ports on the server? Any guides and or resources are highly appreciated Here is my current code.

import socket

def Main():
    host = '127.0.0.1'
    port = 5000

    s = socket.socket()
    s.bind((host, port))

    s.listen(1)
    c, addr = s.accept()
    print('Connection from: ' + str(addr))
    while True:
        data = c.recv(1024)
        if not data:
            break
        print('from connected user: ' + str(data))
        data = str(data).upper()
        print('sending: ' + str(data))
        c.send(data)
    c.close()


if __name__ == '__main__':
    Main()

Upvotes: 6

Views: 9603

Answers (2)

Jonathan Ginsburg
Jonathan Ginsburg

Reputation: 1188

Do Packet Filtering and Translation

An alternative would be to setup packet filtering and translation in the host machine to direct all incoming TCP requests to your process, regardless of the destination port. sshuttle does this to tunnel all requests to an ssh server. This way, your process would not need to open thousands of files.

In freeBSD/macOS the configuration is achieved as follows. Other OSs will have their specific way of doing this (e.g. nftables' nft(8) in Debian).

Configuration File

Create a file (named rules.txt for this example) with the following contents:

# Redirect incoming traffic on interface en0 to localhost:5000
rdr pass on en0 inet proto tcp all -> 127.0.0.1 port 5000

Change en0 to the interface that you wish to intercept incoming connections on. Remove inet or replace with inet6 to accept both IP and IPv6 or just IPv6, respectively. Check pf.conf(5) for exact semantics and syntax of this file.

Enable Rules

With administrative access run the following to load up the rules contained in the previously created file.

Enable packet filtering and translation:

pfctl -e

Flush everything (be careful as this will erase existing routing and translating configurations already set):

pfctl -F a

Load the rules:

pfctl -f rules.txt

Test it out.

Also Include Outgoing Traffic

If you also want to include outgoing traffic, as sshuttle does, you should append the next line to rules.txt:

pass out route-to lo0 inet proto tcp all

You can also tweak this rule to be more selective and avoid setting yourself a networking jail (see entry 1 of notes below).

Notes

  1. If you include outgoing traffic, you will be unable to communicate with the outside world unless you receive a connection first or have an alternative interface. This is because outgoing traffic will be routed to your catchall process (due to the route-to keyword).
  2. Beware that this method allows processes bound to localhost to be reachable from the outside. In the setup above, anyone connecting to any port on en0 will be able to talk to the process bound to 127.0.0.1:5000.
  3. Remember to reload the rules after changing rules.txt for them to take effect.
  4. To disable packet filtering and translation run pfctl -d.

Upvotes: 1

Oguz Ozcan
Oguz Ozcan

Reputation: 1537

You may try all possible ports and store them in a list. Remember ports below 1024 are reserved and some of the ports may be in use. So, you will get some errors and you need to handle those if you cannot bind to that port. Also, you need a socket for each port since a socket can only listen at one port. Create a function create_socket which returns socket, then store them is a list. If you get error while trying to connect, just pass those errors. This may not be a good approach but it will work for you.

def create_socket(port_number):
    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', port_number))
    server_socket.listen(1)

    return server_socket

socket_list = []

for port_number in range(1025,65536):
    try:
        socket_list.append(create_socket(port_number))
    except Exception: 
        pass        

Upvotes: 8

Related Questions