Search code examples
pythonpython-3.xsocketsconnectionport

Check If Port is Open in Python3?


In python 3 Given an IP address, I want to check if a specefic port is open for TCP Connection. How can I do that?

Please Note, I don't want to wait at all. If no response was recieved immediately then just report it's closed.


Solution

  • This is a Python3 example I got from https://www.kite.com/python/answers/how-to-check-if-a-network-port-is-open-in-python

    import socket
    
    a_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    
    port = 8080
    location = ("127.0.0.1", port)
    check = a_socket.connect_ex(location)
    
    if check == 0:
       print("Port is open")
    else:
       print("Port is not open")