How to create an UDP port scanner in python 3?

Asked

Viewed 819 times

1

My code is always "port is opened". My idea is: if the destination responds, the door is open. Otherwise, it may be filtered...

#####################################
# Portscan UDP        #
# #
#####################################
# -*- coding: utf-8 -*-
#!/usr/bin/python3
import socket

ip = (input("Type IP or Address: "))

ports = []
count = 0

while count < 5:
    ports.append(int(input("Type the port: ")))
    count += 1


for port in ports:
    client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    client.bind((ip, port))
    msg = 'hi'
    client.sendto(msg.encode(), (ip,port))
    data, address = client.recvfrom(1024)
    #print("Recebida ->", str(data))




    if data != None:
         print (str(port) + " -> Port is opened")
    else:
         print (str(port) + " -> Port is closed")

print ("Scan Finished")
  • But what’s the problem? I ran the code and everything seems fine, an exception is thrown when the port is in use

  • Always gives that all the doors are open. Apparently does not work!

  • Nop, well try to put there the 80. In my soon generates an exception. More precisely: PermissionError: [Errno 13] Permission denied

  • Has to run as root!

1 answer

2


See if this one works:

import socket

ip = '127.0.0.1'
while True:
    port = input('port?\n')
    if(port == 'exit'): break
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        s.connect((ip, int(port)))
        print('Port {} open'.format(port))
    except:
        print('Port {} not open'.format(port))
    s.close()
  • I’ll test it. Thank you, @Miguel

  • 1

    You can check with nmap: sudo nmap -ss -O -p 80 127.0.0.1 ... "-p..." is the door you want to check, in this case it is 80

  • thanks! It worked

  • Hehe still well @Paulsigonoso, I saw that asked also on Soen but no answer yet. If you get an answer there tell me here with the respective link, because I’m curious about other ways to do

  • You can leave! Thank you. I’m learning a lot here!

  • 2

    Look I’ll edit @Paulsigonoso, I noticed a bug... if you test port 80 for more than once it starts to give as "not open". But I’ve corrected and I’ll put

  • I also asked another question: How to create a TCP port scanner using the SYN (TCP SYN) method? The only one I did "more or less" was the TCP scan "normal".

  • 1
Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.