How to know when it's possible to bind a socket on an unprivileged port?

Giampaolo Rodola' gnewsg at gmail.com
Thu Dec 11 21:00:28 CET 2008


Another way (probably more reliable):


def bind_on_privileged_ports():
    """Return True if it is possible to bind sockets on privileged
    ports (< 1024)."""
    for port in range(1, 1024)[::-1]:
        print port
        try:
            s = socket.socket()
            s.bind((HOST, port))
        except socket.error, err:
            if err[0] == errno.EACCES:
                return False  # speedup
        else:
            s.close()
            return True
    else:
        s.close()
        return False



--- Giampaolo
http://code.google.com/p/pyftpdlib/



More information about the Python-list mailing list