Sunday, April 20, 2025

TCP Port Checker - Check If Remote Port is Open and Listening

import socket
from datetime import datetime

#how to check if tcp port is active

ip = input('Target IP: ')
port_target = input("Port to check: ")

#time_start = datetime.now()

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.setdefaulttimeout(1)
res = s.connect_ex((ip, int(port_target)))

if res == 0:
	print('Port Open')
else:
	print('Port Closed')

#time_stop = datetime.now()
#time_used = time_stop - time_start
#print('Done in:', time_used)

This script allows you to check whether a TCP port on a remote host is open or closed. Here is what the code does:

  1. Imports the socket module for socket programming, and datetime module for measuring the time taken to check the port.
  2. Prompts the user to enter the IP address of the target and the port number they want to check.
  3. Creates a socket object with the AF_INET family (IPv4) and SOCK_STREAM type (TCP protocol).
  4. Sets the default timeout for the socket object to 1 second.
  5. Calls the connect_ex() method on the socket object, passing in the target IP and port number as a tuple. The method returns an error code, which is stored in the variable res.
  6. Checks the value of res. If it is 0, then the port is open. Otherwise, the port is closed.
  7. Prints the result to the console.

Note that the script uses connect_ex() instead of connect(). The difference between the two is that connect() raises an exception if the connection fails, while connect_ex() returns an error code instead. In this case, using connect_ex() allows the script to handle connection failures more gracefully.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...