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

0 thoughts on 'Python Script 15: Creating A Port Scanner In 8 Lines Of Python'
Leave a comment:


*All Fields are mandatory. **Email Id will not be published publicly.


SUBSCRIBE
Please subscribe to get the latest articles in your mailbox.


Recent Posts:






© 2017-2019 Python Circle   Contact Us   Advertise with Us