import socket
def is_valid_ipv4_address(address):
try:
socket.inet_pton(socket.AF_INET, address)
except AttributeError: # no inet_pton here, sorry
try:
socket.inet_pton()
except socket.error:
return False
return address.count('.') == 3
except socket.error: # not a valid address
return False
return True
def is_valid_ipv6_address(address):
try:
socket.inet_pton(socket.AF_INET6, address)
except AttributeError: # no inet_pton here, sorry
try:
socket.inet_pton()
except socket.error:
return False
return address.count('.') == 3
except socket.error: # not a valid address
return False
return True
def checkStatus():
websiteToCheck = input("Enter IP: ").replace(" ", "")
if is_valid_ipv4_address(websiteToCheck) or is_valid_ipv6_address(websiteToCheck):
print("Valid")
elif len(websiteToCheck) == 0:
print("Please input something")
else:
print("Invalid")
checkStatus()
当它无效时给出预期的输出,例如当数字超过255,输入包含字母等字母时。但是,让我们输入10.111.111.111作为我的IP。它打印"有效",即使您现在尝试访问该IP,也会失败。
如何检查IP是否在线,而不是它是否在数字上有效?
答案 0 :(得分:1)
您无法通过简单地查看是否可以访问IP。您需要尝试连接或ping它。后者很容易,虽然不是100%准确(并非所有IP都响应ping)
快捷方式:
import os
response = os.system("ping -c 1 " + address)
#check the response...
if response == 0:
return True
else:
return False