开发者

Python Socket Timeout Issue. How do control the flow of this code better?

开发者 https://www.devze.com 2023-03-06 15:10 出处:网络
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

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)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号