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.
https://docs.python.org/3/library/socket.html