How to check port access by Python

from socket import socket, gethostbyname, AF_INET, SOCK_STREAM
import time

'''
Function to check the availability of computer by port.
host - IP-address or computer name
port - port number
count - number of times to repeat the request on port
timeout - amount of seconds between echo requets on port
'''


def is_port(host="127.0.0.1", port=1433, count=1, timeout=1):
checked = False
    for i in range(count):
        ip = gethostbyname(host)
        sock = socket(AF_INET, SOCK_STREAM)
        result = sock.connect_ex((ip, port))
        if result == 0:
            print("*** port is available! ***")
            checked = True
            break
        sock.close()
        time.sleep(timeout)
        if not checked:
            print("*** port is NOT available! ***")
   return checked 
Реклама