Home > Enterprise >  Check If Port is Open in Python3?
Check If Port is Open in Python3?

Time:12-28

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.

CodePudding user response:

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 result == 0:
   print("Port is open")
else:
   print("Port is not open")

CodePudding user response:

You can use simple script

#!/usr/bin/python

import socket

host = "127.0.0.1"
port = 9003

# try to connect to a bind shell
try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((host, port))
    print(f"Port {port} is open")
    s.close()
except socket.error:
    print(f"Port {port} closed.")

Constant socket.SOCK_STREAM here response for TCP connection.

CodePudding user response:

You can do something like this to check if a port is taken or if it's open:

import socket

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

location = ("127.0.0.1", 80)
result = sock.connect_ex(location)

if result == 0:
   print("Port is open")
else:
   print("Port is closed")

In this, the socket.AF_INET specifies the IP address family (IPv4) and socket.SOCK_STREAM specifies the socket type (TCP).

  • Related