January 13th, 2004, 10:40 PM
Noobish socket question
I feel so ignorant...
But what's the quickest/easiest way to tell if a socket is connected, i.e., open? There's gotta be some flag I can mask to check, or a really easy way...
January 13th, 2004, 10:53 PM
Here. I suppose you have some socket knowledge so I won't go into much explaining.
connect_ex(ip,port) is a simple method that returns 0 if the connection worked or some error error number if it failed.
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
ip = "127.0.0.1" #change to scan another machine
port = 10000 #or whatever you wish
if not s.connect_ex((ip, port)):
print 'Port open.'
print 'Port closed.'
January 13th, 2004, 10:57 PM
Hey, that's dandy. Because if the socket wasn't open, I wanted to open it anyway
But just for future reference, does anyone know of a simple test to check if a socket is open (without disconnecting it if it is, or connecting it if it isn't)?
Thanks for the prompt response, SolarBear =)
January 14th, 2004, 03:29 AM
You could always wrap connect() in a try-except statment, if it doesn't connect at first you can then get a usful error message if you want. Also if you put this inside a while loop you can have it try and connect whenever the connection is dropped.
Sorry, no example for ya
January 14th, 2004, 03:55 PM
I DO have one example - maybe not what you're looking for, but heh. Here's a simple threaded port scanner I wrote. Nothing fancy - plus it hangs if you specify too many ports - but it works !
This does what you asked for, though : by calling connect or connect_ex, you try connection to the remote host : if it worked you stay connected and if it didn't... well you obviously can't connect anyway !
# Zero24's single IP port scanner V1.0
# V1.3.1 by SolarBear
if not s.connect_ex((ip, n)):
t_number -= 1
ip = socket.gethostbyname(socket.gethostname()) #local IP
Sport = input("Please enter the start port number: ")
Eport = input("Please enter the end port number: ")
Eport = Eport + 1
print "You are scanning", ip
print "for ports", Sport,"to", Eport - 1
openports = 
sockets = [socket.socket(socket.AF_INET,socket.SOCK_STREAM) for i in range(Sport,Eport)]
open_lock = thread.allocate_lock()
t_number = Eport - Sport
t_lock = thread.allocate_lock()
for n in range(Sport, Eport):
while t_number > 0: pass
if len(openports) > 0:
openports = sort(openports)
print "Open ports: ",openports
else: print "No open ports. Sorry."