Python 套接字超时问题。如何更好地控制这段代码的流程?
在使用 python 2.7 中的套接字库时,我遇到了让代码按照我想要的方式流动的问题。我希望代码能够迭代一系列 IP 地址,并为该范围内的每个 ip 打开一个套接字连接。如果连接超时,则打印错误并移至该范围中的下一个地址。我使用 for 循环来完成此操作,但是每当套接字遇到超时时,循环就会中断。我做错了什么?我假设这是处理异常的方式。有人能指出我正确的方向吗?
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)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我相信你不能在超时套接字上调用 s.recv(2048) 。我认为修改后的代码应该可以正常工作。
You cannot call s.recv(2048) on a timedout socket I believe. I think this modified code should work fine.
你不用这个干什么?
What aren't you using this?