Search code examples
python-2.7loopsnetworkingport-scanning

How do I loop ports to scan?


I have this problem with a portscanner which keeps hanging at scanning port 1. How can I solve this problem?

    #! /usr/bin/env python

    import socket 
    import subprocess
    from datetime import datetime

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

    def portscan():
        server = raw_input("Enter the server to scan: ")
        serverIP = socket.gethostbyname(server)

        # Printing banner with information about host
        print "[+] Host: {} [+]\nIP Address: {}\n".format(server, serverIP)
        print "[!] Please wait, scanning for open services...\n"

        #Time when scan started.
        t1 = datetime.now()

        try:
            for port in range(1, 1024):
                sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                result = sock.connect_ex((serverIP, port))
                if result == 0:
                    print "[+] Port {}: Status:OPEN\n".format(result)
                    sock.close()

        except socket.gaierror:
            print "Hostname could not be resolved, Exiting...\n"
            sys.exit()

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

        #Checking time again
        t2 = datetime.now()
        #Calculate duration of scan
        totaltime = t2 - t1

        print "Scan completed, duration: {}\n".format(totaltime)  

What happens when i run it i give it a hostname and resolve it to a IP Address but whenever the scan starts it keeps scanning port 1 as i saw in Wireshark


Solution

  • I think that you maybe need a timeout.

    Eventually, your sock.connect_ex( ), will to raise an exception socket.error: [Errno 110] Connection timed out, as you can read more about it, in this answer.

    But the default timeout could be 120 seconds, and maybe you don't want to wait so much. So, you can set your own timeout, like that:

    try:
        for port in range(1, 1024):
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.settimeout(10) #timeout set for wait up 10 seconds.
            result = sock.connect_ex((serverIP, port))
            sock.settimeout(None)
    
    

    To know why to use sock.settimeout(None), and see another ways of setting timeout, you can read this discussion.

    I'm not sure if it was what you're looking for, but I hope it may help.