[Tutor] Help with error handling in a while loop

Mark Kels mark.kels at gmail.com
Fri Feb 18 17:29:59 CET 2005

Hi all.
I'm trying to build a simple port scanner (just to learn sockets).
here is the code (doesn't work) :
import socket
sk=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host=raw_input("Enter name of host to scan: ")
start_port=input("Enter the start port: ")
end_port=input("Enter the end port: ")
while start_port<end_port:
        print "port",start_port,"is open on",host
        print "Port",start_port,"is closed on",host


As you can see, when there is an exception the socket closes (I run
the program from idle,  so I don't need to exit it).
An exception will be every time the connection fails (because the port
is closed ).
I want it to print the text and go back and continue the loop whenever
there is an exception, how do I do that ?

Thanks in advance.

1. The day Microsoft makes something that doesn't suck is probably the
day they start making vacuum cleaners.
2. Unix is user friendly - it's just picky about it's friends.
3. Documentation is like sex: when it is good, it is very, very good.
And when it is bad, it is better than nothing. - Dick Brandon

More information about the Tutor mailing list