Subnet Port Scanner in Python Using the socket and ipaddress Modules
When you manage or troubleshoot a network, you may need to determine which hosts in a subnet are listening on a particular TCP port. For example, checking port 22 can help identify systems where the SSH service is available.
Usually, when I wanted to do this in Linux shell, I used to create a file containing IP addresses, read them one by one, and use nc(netcat) command to check for open port.
In Python, things become easier and more powerful at the same time. You don’t need to specify the addresses in the subnet manually. There is a built-in module, ipaddress, which provides the ip_network() function.
This function takes a subnet as an argument and returns a network object representing that subnet:
import ipaddress
subnet = ipaddress.ip_network("10.10.10.0/28")
print(type(subnet))
<class 'ipaddress.IPv4Network'>Now we have this object, but what can we do with it. Can we iterate over it? Let us try:
for ip in subnet:
print(ip)
10.10.10.0
…
10.10.10.15You can see that we only have to use a for loop to get all the addresses and process them as we like.
But that is not all — we can also easily obtain different network information, such as the network address, broadcast address, netmask in x.y.z.w format, and the total number of addresses. And, as the cherry on top, we can get a list of all usable host addresses.
Just look at this code:
print(subnet.network_address)
10.10.10.0
print(subnet.num_addresses)
16
print(subnet.broadcast_address)
10.10.10.15
print(subnet.hosts())
<generator object _BaseNetwork.hosts at 0x000001FE9A102CE0>When we check for open ports on subnet IPs, we will exclude network address and the broadcast address, so hosts() will be useful.
hosts = subnet.hosts()Now, we can iterate through useful IPs in the subnet, but how can we check if a port is open? I will talk specifically about TCP port, because UDP is different- it doesn’t create a connection, and might not send response, even if it is open.
For each individual IP address, we can test whether a TCP port is open by creating a socket and trying to establish a connection to that IP address and the desired port. I will use port 22, which is the default port for the SSH protocol and is commonly used for encrypted remote connections.
We need to import socket module:
import socketsocket module has function of the same name, socket, that creates a client socket- an IP address/port pair that will connect to remote IP/port pair.
client = socket.socket()We called it client because it will try to connect on port 22 to IPs from the subnet. Now the configuration part- we can try to connect, but we don’t want the client trying to connect for too long-it will wait for long time, until something like operating system decides to abort the connection. We can fortunately set this timeout to be something reasonable, like 1 second. If there is a response, it will usually take much less time. This is configured with:
client.settimeout(1)Now we can try to connect:
result = sock.connect_ex((ip, port))We are not using the more common connect() function (discussed in one of my previous articles), but its close cousin, connect_ex().
Get Jasenko Krejić’s stories in your inbox
Join Medium for free to get updates from this writer.
When the connection fails, connect() raises an exception, while connect_ex() returns 0 on success and a non-zero integer error code if the connection fails for any reason. We will not inspect these error codes; we will simply react when 0 (success) is returned. This is a full for loop:
for ip in subnet:
client = socket.socket()
client.settimeout(1)
result = client.connect_ex((str(ip), port))
if result == 0:
print(f"Port {port} on {ip} is open")There are some important details here: when passing an argument to connect_ex() method, you need to take care that it is a tuple- so, notice the extra pair of parenthesis. Also, in this tuple, you can not pass and ip directly, because it is an IPv4Address type of object, and first element should be string.
print(type(ip))
<class 'ipaddress.IPv4Address'>This is simple to resolve, because we can use str function to convert it to string. And that is exactly what we did.
Let us run the program and suppose that we have two open SSH ports on our hypothetical 10.10.10.0/28 network. We will get the following output:
Port 22 on 10.10.10.2 is open
Port 22 on 10.10.10.4 is openYou have seen a practical use of Python socket and ipaddress modules: scanning the IP addresses in a subnet and checking whether a particular TCP port is open. The ipaddress module makes it easy to iterate through IPv4 network subnet addresses ,and socket provides the way to attempt connections to each IP. Using connect_ex()allows connection results to be handled through return codes rather than exceptions, like connect() does.
This is only a small subset of what these two modules can do. The socket module supports many more features, including TCP and UDP communication, creating client and server applications, hostname and address resolution, service name lookups and so on.
ipaddress has features for working with IP addresses, networks, subnetting, address validation, network membership, just to name most important ones.
The subnet port scanner presented here is just a simple introduction to combining these two powerful built-in modules rather than as a comprehensive demonstration of their capabilities, which are discussed in my other articles.
If you found this article helpful, consider supporting my work with a small donation on Ko-fi:
https://ko-fi.com/jasenko/donate
If you are learning Python, and want to follow the PCEP Python exam syllabus, check my newest Udemy Course, it is a video tutorial packed with hands-on example, quizzes, coding exercises and two full mock exams:
https://www.udemy.com/course/pass-python-pcep-30-0x-video-lessons-and-mock-tests-2025/
If you want to learn more about AWS Lightsail service, check my course on Udemy on AWS Lightsail.
https://www.udemy.com/course/aws-lighsail-a-different-perspective
Also, if you want to prepare for the basic AWS Certified Cloud Practitioner exam, check another one of my courses, also on Udemy:
https://www.udemy.com/course/aws-certified-cloud-practitioner-crash-course







