Python – Simple Port Scanner with Sockets
Ports can be scanned to check which ports are engage and which ports are open or free. In Python “Socket” module provides access to the BSD socket interface, which is available on all platforms.
To scan port following steps can be implemented:
1] Recognize host’s ip address
2] Create new socket
3] Forming a connection with port
3] Checks weather data is received or not
5] Close connection
To use socket module ,we have to import it :
Let’s see some more functions from socket module that can be used to create simple port scanner
To create a new object of socket socket() is used. The syntax of socket() function is:
newSocket = socket.socket(socket_family, socket_type)
socket_family is ip address of version 4 or 6.By default it takes as IPV4.
AF_INET for socket family of address version 4 AF_INET6 for socket family of address version 6
socket_type is type of connection.by default it takes as TCP connection.
SOCK_STREAM for Socket type of TCP connections SOCK_DGRAM for Socket type of UDP connections
To Return a string containing the hostname of the machine where the Python interpreter is currently executing. we can use :
If hostname is in IPV6 Following method is used Translate a host name to IPv4 address format. The IPv4 address is returned as a string, such as ‘10.120.30.2’. If the host name is an IPv4 address itself it is returned unchanged.
To Bind the socket to address, we use bind()method .The socket must not already be bound.The format of address depends on the address family.Syntax of this function is as follows.
To close connection close()method is used.This method mark the socket closed. Once that happens, all future operations on the socket object will fail. The remote end will receive no more data (after queued data is flushed).Sockets are automatically closed when they are garbage-collected, but it is recommended to close() them explicitly, or to use a with statement around them. Syntax is :
Let us see actual code to scan ports.