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 en开发者_如何学Ccounters 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)
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)
What aren't you using this?
if socket.timeout:
print("Timed out.")
else:
data = s.recv(2048)
print(data)
精彩评论