Skip to content
Related Articles
Open in App
Not now

Related Articles

Python – Simple Port Scanner with Sockets

Improve Article
Save Article
  • Last Updated : 27 Jul, 2020
Improve Article
Save Article

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 :

 import socket  

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 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 ‘’. 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.

#Python code for simple port scanning
import socket  #importing library 
ip = socket.gethostbyname (socket.gethostname())  #getting ip-address of host
for port in range(65535):      #check for all available ports
        serv = socket.socket(socket.AF_INET,socket.SOCK_STREAM) # create a new socket
        serv.bind((ip,port)) # bind socket with address
        print('[OPEN] Port open :',port) #print open port number
    serv.close() #close connection

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!