Fast way to test if a port is in use using Python

To check port use:

def is_port_in_use(port: int) -> bool:
    import socket
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        return s.connect_ex(('localhost', port)) == 0

source: https://codereview.stackexchange.com/questions/116450/find-available-ports-on-localhost

Note:
connect_ex cann still raise an exception (in case of bad host name i.e see docs on [1].

[1] https://docs.python.org/3/library/socket.html

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)