Blog available for sell
This blog is available for sale. Please 'contact us' if interested.
Advertise with us
socket   0   9728
Python Script 15: Creating a port scanner in 8 lines of python

Python's socket module is used for network programming. This module provides access to the BSD socket interface. 

Lets say you want to scan the system with IP address in your local area network, use below piece of code to scan ports in range 1 to 1024.

import socket

for port in range(1, 1025):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex(("", port))
if 0 == result:
print("Port: {} Open".format(port))

socket() function returns a socket object. 

The address format required by a particular socket object is automatically selected based on the address family specified when the socket object was created.

For AF_INET address family, address is a pair of host and port where host is a string representing either a hostname in Internet domain notation like '' or an IPv4 address like, and port is an integer.

socket.SOCK_STREAM constant represent the socket types, used for the second argument to socket() function.

connect_ex() method return an error indicator in case of any exception unlike connect() method which raise an exception. In case of no error, 0 is returned.

When above script is executed for host (IP address of my router), it returns below result. 



socket   0   9728
0 comments on 'Python Script 15: Creating A Port Scanner In 8 Lines Of Python'
Login to comment

DigitalOcean Referral Badge

© 2022-2023 Python Circle   Contact   Sponsor   Archive   Sitemap