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:
- Imports the
socket
module for socket programming, anddatetime
module for measuring the time taken to check the port. - Prompts the user to enter the IP address of the target and the port number they want to check.
- Creates a
socket
object with theAF_INET
family (IPv4) andSOCK_STREAM
type (TCP protocol). - Sets the default timeout for the
socket
object to 1 second. - Calls the
connect_ex()
method on thesocket
object, passing in the target IP and port number as a tuple. The method returns an error code, which is stored in the variableres
. - Checks the value of
res
. If it is 0, then the port is open. Otherwise, the port is closed. - 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