Open In App

Threaded Port Scanner using Sockets in Python

Improve
Improve
Like Article
Like
Save
Share
Report

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

Threading is a complex topic, but it can be broken down and conceptualized as a methodology where we can tell the computer to do another task if the processor is experiencing idle time. In the case of port scanning, we are spending a lot of time just waiting on the response from the server. While we are waiting, we can do something else. That is what threading is used for. 

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

Python3




import threading
from queue import Queue
import time
import socket
  
# a print_lock is used to prevent "double"
# modification of shared variables this is
# used so that while one thread is using a
# variable others cannot access it Once it
# is done, the thread releases the print_lock.
# In order to use it, we want to specify a
# print_lock per thing you wish to print_lock.
print_lock = threading.Lock()
  
# ip = socket.gethostbyname(target)
target = 'localhost'
  
def portscan(port):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        con = s.connect((target, port))
        with print_lock:
            print('port is open', port)
        con.close()
    except:
        print('port is close', port)
  
  
# The threader thread pulls a worker 
# from a queue and processes it
def threader():
    while True:
        # gets a worker from the queue
        worker = q.get()
  
        # Run the example job with the available 
        # worker in queue (thread)
        portscan(worker)
  
        # completed with the job
        q.task_done()
  
  
# Creating the queue and threader
q = Queue()
  
# number of threads are we going to allow for
for x in range(4):
    t = threading.Thread(target=threader)
  
    # classifying as a daemon, so they it will
    # die when the main dies
    t.daemon = True
  
    # begins, must come after daemon definition
    t.start()
  
  
start = time.time()
  
# 10 jobs assigned.
for worker in range(1, 10):
    q.put(worker)
  
# wait till the thread terminates.
q.join()


Output: 

port is close 2
port is close port is close 4
port is closeport is close 1
 53

port is close 6port is close
 7
port is close 8
port is close 9


Last Updated : 28 Aug, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads