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!"
-
7Your indentation seems to be off.keyser– keyser2013年12月11日 22:28:37 +00:00Commented Dec 11, 2013 at 22:28
1 Answer 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.