• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
PythonForBeginners.com

PythonForBeginners.com

Learn By Example

  • Home
  • Learn Python
    • Python Tutorial
  • Categories
    • Basics
    • Lists
    • Dictionary
    • Code Snippets
    • Comments
    • Modules
    • API
    • Beautiful Soup
    • Cheatsheet
    • Games
    • Loops
  • Python Courses
    • Python 3 For Beginners
You are here: Home / Code Snippets / Port scanner in Python

Port scanner in Python

Author: PFB Staff Writer
Last Updated: January 4, 2023

This post will show how you can make a small and easy-to-use port scanner program written in Python. There are many ways of doing this with Python, and I’m going to do it using the built-in module Socket.

Table of Contents
  1. Port Scanner Using Sockets in Python
  2. Socket Functions
  3. Writing a program using Python Sockets
  4. Conclusion

Port Scanner Using Sockets in Python

The socket module in Python provides access to the BSD socket interface. It includes the socket class, for handling the actual data channel, and functions for network-related tasks such as converting a server’s name to an address and formatting data to be sent across the network.

Sockets are widely used on the Internet, as they are behind any kind of network communications done by your computer. The INET sockets account for at least 99% of the sockets in use. The web browsers that you use open a socket and connect to the web server.

Any network communication goes through a socket.

For more reading about the socket module, please see the official documentation.

Socket Functions

Before we get started with our sample program, let’s see some of the socket functions we are going to use.


Syntax for creating a socket
sock = socket.socket (socket_family, socket_type)

Creates a stream socket
sock = socket.socket (socket.AF_INET, socket.SOCK_STREAM)

AF_INET 
Socket Family (here Address Family version 4 or IPv4) 

SOCK_STREAM Socket type TCP connections 

SOCK_DGRAM Socket type UDP connections 

Translate a host name to IPv4 address format 
gethostbyname("host") 

Translate a host name to IPv4 address format, extended interface
socket.gethostbyname_ex("host")  

Get the fqdn (fully qualified domain name)
socket.getfqdn("8.8.8.8")  

Returns the hostname of the machine..
socket.gethostname()  

Exception handling
socket.error

Writing a program using Python Sockets

How to make a simple port scanner program in Python?

This small port scanner program will try to connect on every port you define for a particular host. The first thing we must do is import the socket library and other libraries that we need.

Open up a text editor, copy & paste the code below.

Save the file as “portscanner.py” and exit the editor

#!/usr/bin/env python
import socket
import subprocess
import sys
from datetime import datetime

# Clear the screen
subprocess.call('clear', shell=True)

# Ask for input
remoteServer    = raw_input("Enter a remote host to scan: ")
remoteServerIP  = socket.gethostbyname(remoteServer)

# Print a nice banner with information on which host we are about to scan
print "-" * 60
print "Please wait, scanning remote host", remoteServerIP
print "-" * 60

# Check what time the scan started
t1 = datetime.now()

# Using the range function to specify ports (here it will scans all ports between 1 and 1024)

# We also put in some error handling for catching errors

try:
    for port in range(1,1025):  
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        result = sock.connect_ex((remoteServerIP, port))
        if result == 0:
            print "Port {}: 	 Open".format(port)
        sock.close()

except KeyboardInterrupt:
    print "You pressed Ctrl+C"
    sys.exit()

except socket.gaierror:
    print 'Hostname could not be resolved. Exiting'
    sys.exit()

except socket.error:
    print "Couldn't connect to server"
    sys.exit()

# Checking the time again
t2 = datetime.now()

# Calculates the difference of time, to see how long it took to run the script
total =  t2 - t1

# Printing the information to screen
print 'Scanning Completed in: ', total

Let’s run the program and see what the output looks like:

$ python portscanner.py

Enter a remote host to scan: www.your_host_example.com
------------------------------------------------------------
Please wait, scanning remote host xxxx.xxxx.xxxx.xxxx
------------------------------------------------------------

Port 21:   Open
Port 22:    Open
Port 23:    Open
Port 80:    Open
Port 110:   Open
Port 111:   Open
Port 143:   Open
Port 443:   Open
Port 465:   Open
Port 587:   Open
Port 993:   Open
Port 995:   Open

Scanning Completed in:  0:06:34.705170

You can observe in the above example that the port scanner scans all the ports in the device and mentions if the ports are open or closed.

Conclusion

In this article, we have discussed a python program using the socket module to create a port scanner. This program is intended for individuals to test their own equipment for weak security, and the author will take no responsibility if it is put to any other use.

To learn more about python programming, you can read this article on python simplehttpserver. You might also like this article on the hangman game in python.

Related

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Enroll Now

Filed Under: Code Snippets, Scripts Author: PFB Staff Writer

More Python Topics

API Argv Basics Beautiful Soup Cheatsheet Code Code Snippets Command Line Comments Concatenation crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Pyspark Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2

Primary Sidebar

Menu

  • Basics
  • Cheatsheet
  • Code Snippets
  • Development
  • Dictionary
  • Error Handling
  • Lists
  • Loops
  • Modules
  • Scripts
  • Strings
  • System & OS
  • Web

Get Our Free Guide To Learning Python

Most Popular Content

  • Reading and Writing Files in Python
  • Python Dictionary – How To Create Dictionaries In Python
  • How to use Split in Python
  • Python String Concatenation and Formatting
  • List Comprehension in Python
  • How to Use sys.argv in Python?
  • How to use comments in Python
  • Try and Except in Python

Recent Posts

  • Count Rows With Null Values in PySpark
  • PySpark OrderBy One or Multiple Columns
  • Select Rows with Null values in PySpark
  • PySpark Count Distinct Values in One or Multiple Columns
  • PySpark Filter Rows in a DataFrame by Condition

Copyright © 2012–2025 · PythonForBeginners.com

  • Home
  • Contact Us
  • Privacy Policy
  • Write For Us