Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
How to Build a WiFi Scanner in Python using Scapy?
Next article icon

Simple Port Scanner using Sockets in Python

Last Updated : 12 Jul, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Prerequisites: Socket Programming in Python

Before going to the programming, let us discuss about ports. In this article, we will check the virtual ports of a server or websites, or localhost. Every port has a unique number. There are 65,535 ports available in a host starting from 0. We can assign the ports for any services.

Example 1: In this program, you can scan a number of ports in a certain range.

Python3
# Here we import two modules, socket and time  import socket import time  s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # here we asking for the target website # or host target = input('What you want to scan?: ')  # next line gives us the ip address # of the target target_ip = socket.gethostbyname(target) print('Starting scan on host:', target_ip)  # function for scanning ports   def port_scan(port):     try:         s.connect((target_ip, port))         return True     except:         return False   start = time.time()  # here we are scanning port 0 to 4 for port in range(5):     if port_scan(port):         print(f'port {port} is open')     else:         print(f'port {port} is closed')  end = time.time() print(f'Time taken {end-start:.2f} seconds') 

  

Output: 
 


 

What you want to scan?: localhost Starting scan on host: 127.0.0.1 port 0 is closed port 1 is closed port 2 is closed port 3 is closed port 4 is closed Time taken 8.12 seconds


 

Note: you can change the range in the for loop for change the number of ports to be scanned. For scanning a website or a host it can take a certain time so be patient.


 

Example 2: If you want to scan a particular port then go for this solution.


 

Python3
# importing the sockets module import socket  s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) target = input('What you want to scan?: ')  # getting the ip address using gethostbyname # function t_IP = socket.gethostbyname(target) print("Starting scan on host: ", t_IP)   def port_scan(port):     try:         s.connect((t_IP, port))         return True     except:         return False   port = int(input("Enter the port number to be scanned: "))  if port_scan(port):     print('Port', port, 'is open') else:     print("port", port, "is closed") 

Output:

What you want to scan?: localhost Starting scan on host:  127.0.0.1 Enter the port number to be scanned: 135 Port 135 is open

Note: Here we are scanning the localhost. You can scan any host or website. If you are getting any error then sockets is unable to connect the target or perhaps you did some mistake in your code.

Warnings: Without taking permission from the administration scanning ports of a server or a website can be considered as a crime. There are many free websites available for testing, you can use them.


Next Article
How to Build a WiFi Scanner in Python using Scapy?

S

santanunandi01
Improve
Article Tags :
  • Python
  • Python-socket
Practice Tags :
  • python

Similar Reads

  • Python - Simple Port Scanner with Sockets
    Ports can be scanned to check which ports are engaged 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 the ports, the following steps can be implemented: 1] Recognize the host's IP address 2] Create
    2 min read
  • Threaded Port Scanner using Sockets in Python
    Port scanning can be really slow yet, in most cases, is not process intensive. Thus, we can use threading to improve our speed. There can be thousands of possible ports. If it takes 5-15 seconds per port to scan, then we might have a long wait ahead of us without the use of threading. Threading Thre
    2 min read
  • Port Scanner using Python
    Prerequisites: Socket Programming in Python This article is just to provide a sample code to generate a Port Scanner. This Port Scanner will work for both the Web Applications as well as remote Host. This tool has been created to provide the basic functionality of a Port Scanner. The general concept
    2 min read
  • Simple Chat Room using Python
    This article demonstrates - How to set up a simple Chat Room server and allow multiple clients to connect to it using a client-side script. The code uses the concept of sockets and threading. Socket programming Sockets can be thought of as endpoints in a communication channel that is bi-directional
    8 min read
  • How to Build a WiFi Scanner in Python using Scapy?
    In this article, we are going to build a WiFi Scanner in Python using Scapy. WiFi Scanning or Network scanning refers to the scanning of the whole network to which we are connected and try to find out what are all the clients connected to our network. We can identify each client using their IP and M
    3 min read
  • Setting up a simple HTTP server using Python
    In this article, we are going to learn how to set up a simple and local HTTP server using Python. An HTTP server can be very useful for testing Android, PC or Web apps locally during development. It can also be used to share files between two devices connected over the same LAN or WLAN network. Inst
    2 min read
  • GET and POST Requests Using Python
    This post discusses two HTTP (Hypertext Transfer Protocol) request methods  GET and POST requests in Python and their implementation in Python.  What is HTTP? HTTP is a set of protocols designed to enable communication between clients and servers. It works as a request-response protocol between a cl
    7 min read
  • Simple Calculator in Python Socket Programming
    In this article, we are going to know how to make a simple calculator in Python socket programming. Prerequisite: Socket Programming in Python. First, we will understand the basics of Python socket programming. Socket programming is used to set up a communication channel between two nodes on a netwo
    4 min read
  • Network Scanning using scapy module - Python
    Scapy is a library supported by both Python2 and Python3. It is used for interacting with the packets on the network. It has several functionalities through which we can easily forge and manipulate the packet. Through scapy module we can create different network tools like ARP Spoofer, Network Scann
    3 min read
  • Visiting Card Scanner GUI Application using Python
    Python is an emerging programming language that consists of many in-built modules and libraries. Which provides support to many web and agile applications. Due to its clean and concise syntax behavior, many gigantic and renowned organizations like Instagram, Netflix so-and-so forth are working in Py
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences