Port scanning with sockets

Sockets are the fundamental building blocks for network communications, and we can easily check whether a specific port is open, closed, or filtered by calling the connect_ex() method. For example, we could have a script that reads the IP address and a list of ports and return information about each port regarding whether it is open or closed.

You can find the following code in the socket_port_scan.py file:

#!/usr/bin/env python3

import socket

ipaddress =input("Enter ip address or domain for port scanning:")

port_init= input("Enter first port: ")
port_end = input("Enter last port: ")

for port in range(int(port_init), int(port_end)+1):
sock= socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.settimeout(5)
result = sock.connect_ex((ipaddress,port))
if result == 0:
print(port, "--> Open")
else:
print(port, "--> Closed")
sock.close()

This is the output of the previous script over the packtpub.com domain for getting information about the port states between 80 and 85:

Enter ip address or domain for port scanning:www.packtpub.com
Enter first port: 80
Enter last port: 85
80 --> Open
81 --> Closed
82 --> Closed
83 --> Closed
84 --> Closed
85 --> Closed
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset