Blog available for sell
This blog is available for sale. Please 'contact us' if interested.
Advertise with us
socket   0   9408
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 192.168.0.1 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)
sock.settimeout(1)
result = sock.connect_ex(("192.168.0.1", port))
if 0 == result:
print("Port: {} Open".format(port))
sock.close()


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 'pythoncircle.com' or an IPv4 address like 10.10.130.57, 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 192.168.0.1 (IP address of my router), it returns below result. 

eePO2NUxazcAAAAASUVORK5CYII=



References:

https://docs.python.org/3/library/socket.html



socket   0   9408
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