0

I'm having trouble with my code here, when I input a port range when it comes to a closed port the program will just pause. Its fine when it has open ports. Can anyone help?

#!/usr/bin/env python

import sys
import socket
import subprocess

address = raw_input("Which IP would you like to scan?  ")
r1 = input("What starting IP would you like to scan? i.e 10:  ") 
r2 = input("Which ending IP would you like to scan? i.e 300: ")     

print "This can take a while for big port ranges. Scan commencing on", address 

for port in range(r1,r2):    

            sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)        

if(sock.connect_ex((address,port))==0):    
        print "Port " , port, "is open"         
        sock.close()                            
        print " "                                
        print "Scan completed sucessfully"
else: 
    print " "
    print "Scan completed, No ports found!"
MrTurvey
  • 23
  • 3

1 Answers1

1

The problem is that (under most firewalls), the remote computer deliberately won't respond to TCP connection packets coming in to a closed port -- if it did, your connect_ex() call would fail quickly (with errno = ECONNREFUSED). That would allow you to quickly continue on to trying the next port, which is not something firewall designers want to encourage.

So instead they just ignore the incoming TCP packets, and there is no way for your computer to determine whether the remote computer is deliberately ignoring you, or if it's just being slow to respond.

So all you can really do is pick a "reasonable" timeout for yourself and assume that any TCP connections that have not connected successfully within that timeout period must indicate a firewalled port.

As for how to do that in Python, it's pretty straightforward; see here for details.

Community
  • 1
  • 1
Jeremy Friesner
  • 70,199
  • 15
  • 131
  • 234
  • This is working better now, by the fact it can finish a scan so thank you! although for some reason it will only pick up one open port. For example ports 80 and 153 are open. If I scan 79-160 it will pick up 80 and thats all. Any Ideas? – MrTurvey Dec 11 '13 at 22:57
  • Are you calling sock.close() when you are done using the socket? Perhaps the open sockets are piling up until your program isn't allowed to create any more... – Jeremy Friesner Dec 12 '13 at 00:23