我的IP检查员正在检查IP在技术上是否有效,我想检查一下它是否在线

时间:2017-02-20 08:16:59

标签: python python-3.x validation ip

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是否在线,而不是它是否在数字上有效?

1 个答案:

答案 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