我是python的新手。用python 3.6编写
您可以跳过ipRange部分
这是代码:
import socket
def ipRange(start_ip, end_ip):
start = list(map(int, start_ip.split(".")))
end = list(map(int, end_ip.split(".")))
temp = start
ip_range = []
ip_range.append(start_ip)
while temp != end:
start[3] += 1
for i in (3, 2, 1):
if temp[i] == 256:
temp[i] = 0
temp[i-1] += 1
ip_range.append(".".join(map(str, temp)))
return ip_range
ip_range = ipRange("192.168.0.101", "192.168.0.110")
#To this point everything is fine since it is not my code
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(5)
# if i add s.setblocking(1) it works, but it is really slow and not printing
# out "timed out" error message
for ip in ip_range:
try:
con = s.connect((ip, 80))
con.close()
except Exception as msg:
print(ip, msg)
我希望此代码仅打印出ip和异常msg“ ConnectionRefusedError”或套接字“ timed out”错误,但之后每隔一个msg异常是“提供了无效的参数”。
Shell:
192.168.0.101 [WinError 10061] No connection could be made because the
target machine actively refused it #Good
192.168.0.102 [WinError 10061] No connection could be made because the target
machine actively refused it #Good
192.168.0.103 [WinError 10061] No connection could be made because the target
machine actively refused it #Good
192.168.0.104 timed out #Good
192.168.0.105 [WinError 10022] An invalid argument was supplied #Not good
192.168.0.106 [WinError 10022] An invalid argument was supplied #
192.168.0.107 [WinError 10022] An invalid argument was supplied
192.168.0.108 [WinError 10022] An invalid argument was supplied
192.168.0.109 [WinError 10022] An invalid argument was supplied
192.168.0.110 [WinError 10022] An invalid argument was supplied
一切都很好,直到“超时”消息为止。之后,我希望它再次为下一个IP打印“超时”味精或打印出“ ConnectionRefusedError”-这意味着设备已连接到LAN上的该IP。
稍后,我将尝试使此脚本打印出连接到lan的所有设备。
我希望你明白这一点。预先感谢。