0

While working with the sockets library in python 2.7, I am encountering an issue with getting the code to flow the way I want it to. I'd like the code to iterate over a range of IP addresses and open a socket connection for each ip in the range. If the connection times out, print an error and move on to the next address in the range. I'm using a for loop to accomplish this, however whenever the socket encounters a time out, the loop breaks. What am I doing wrong? I'm assuming its the way the exception is being handled. Can anyone point me in the right direction?

from IPy import IP
ip = IP(sys.argv[1])
for x in ip:
 print("Connecting to: {0}".format(str(x)))
 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 s.settimeout(10)
 svr = (str(x), 25)
 s.connect(svr)
 if socket.timeout:
 print("Timed out.")
 data = s.recv(2048)
 print(data)
 continue
print("Range Completed.")
sys.exit(1)
asked May 16, 2011 at 2:09

2 Answers 2

1

You cannot call s.recv(2048) on a timedout socket I believe. I think this modified code should work fine.

from IPy import IP
ip = IP(sys.argv[1])
for x in ip:
 print("Connecting to: {0}".format(str(x)))
 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 s.settimeout(10)
 svr = (str(x), 25)
 s.connect(svr)
 if socket.timeout:
 print("Timed out.")
 else:
 data = s.recv(2048)
 print(data)
 continue
print("Range Completed.")
sys.exit(1)
answered May 16, 2011 at 2:13
Sign up to request clarification or add additional context in comments.

Comments

0

What aren't you using this?

 if socket.timeout:
 print("Timed out.")
 else:
 data = s.recv(2048)
 print(data)
answered May 16, 2011 at 2:12

Comments

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.