HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Find available ports on localhost

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
localhostportsavailablefind

Problem

I'm writing code to find the available ports on 127.0.0.1. I'd like it to be faster, but it's functional now.

def find_open_ports():
    for port in xrange(1,8081):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        res = sock.connect_ex(('localhost', port))
        if res == 0:
            yield port
        sock.close()


and it is called with available_ports = list(find_open_ports()).

There is no error handling because this will be running server-side. If localhost can't be found, there are bigger problems than failing a port scan.

Solution

Two comments:

-
The existing code only checks for free ports under 8081. The full range is 0-65535.

-
You're only checking the IPv4 definition of 'localhost'. We live in the future! IPv6 calls localhost ::1. At first blush, this would seem to not matter - something's either listening or not, right? - but it turns out that firewalls sometimes have different rulesets for IPv4 vs IPv6, so one may get through but the other not. You didn't specify what this code was for, so it's just a caveat to keep in mind.

Context

StackExchange Code Review Q#116450, answer score: 4

Revisions (0)

No revisions yet.