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!"
asked Dec 11, 2013 at 22:27
1
  • 7
    Your indentation seems to be off. Commented Dec 11, 2013 at 22:28

1 Answer 1

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.

answered Dec 11, 2013 at 22:37
Sign up to request clarification or add additional context in comments.

2 Comments

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?
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...

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.