Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python检查网络连接_Python_Networking - Fatal编程技术网

Python检查网络连接

Python检查网络连接,python,networking,Python,Networking,我想知道是否有任何python脚本(最好是命令)可以告诉我是否连接到网络 我说的不是“互联网”,而是有线或无线“网络” (因此请不要将此问题设置为重复) 我的意思是,我的调制解调器路由器已打开,并且我已连接到它(它是否有internet并不重要),因此脚本返回True (最好不要建议使用ping等终端命令) 还有一个问题可能是这个问题的答案: 获取请求。获取('192.168.1.1')。状态\u code好吗?如果是200,我们就连接到网络了 还有一个问题可能是这个问题的答案:获取reques

我想知道是否有任何python脚本(最好是命令)可以告诉我是否连接到网络

我说的不是“互联网”,而是有线或无线“网络” (因此请不要将此问题设置为重复)

我的意思是,我的调制解调器路由器已打开,并且我已连接到它(它是否有internet并不重要),因此脚本返回True (最好不要建议使用ping等终端命令)

还有一个问题可能是这个问题的答案: 获取
请求。获取('192.168.1.1')。状态\u code
好吗?如果是200,我们就连接到网络了

还有一个问题可能是这个问题的答案:获取requests.get('192.168.1.1')、status_代码好吗?如果是200,我们连接到网络上了吗

这不是一个好主意

  • 如果本地网络不是
    192.168.1.0/24
    ,该怎么办
  • 如果网关不是
    192.168.1.1
    ,该怎么办
  • 如果路由器没有HTTP接口怎么办
你能做的唯一明智的事情就是选择一个众所周知的端点(例如“google.com”)并尝试联系它(例如,
requests.get()http://google.com)
)。如果它能工作…太好了,你已经接通了!如果它不起作用,您就没有足够的信息来决定是否连接


如果您只对本地网络连接感兴趣,可以首先确定默认网关地址(例如,在Linux下运行
ip路由
,或在Windows上运行
route print
),然后尝试ping该地址。再一次,你只能检测到一个积极的结果:如果你得到一个回应,你就被联系上了,但是如果你没有,你就不知道你是否被联系上了。

拉尔克斯所说的一切都是正确的。 另外,您可以检查主机(或仅本地主机)上是否有IP地址

您可以做什么:

  • 检查方框中是否有IP地址,该地址与本地主机、环回地址范围不同

  • 如果您知道默认网关(您可以得到它),您可能会ping默认网关-但这可能会失败,因为该默认网关上可能禁用了ICMP ping数据包

为了避免TOCTOU错误,只需使用地址并捕捉错误! (见:)

以下是我在该上下文中通常使用的函数:

def get_host_ip_or_localhost() -> Union[str, None]:
    """
    >>> result = get_host_ip_or_localhost()
    >>> assert is_valid_ip_adress(result)
    """
    host_ip = get_host_ip()

    if not host_ip:                                                                     # pragma: no cover
        logger.warning('can not get default gateway IP, setting localhost as IP')       # pragma: no cover
        host_ip = socket.gethostbyname('localhost')                                     # pragma: no cover
    return host_ip


def ip_is_localhost(host_ip: str) -> bool:
    """
    >>> ip_is_localhost('127.0.0.1')
    True
    >>> ip_is_localhost('localhost')
    True
    >>> ip_is_localhost('192.168.168.17')
    False
    >>> ip_is_localhost('192.168.168.254')
    False
    """
    host_ip = socket.gethostbyname(host_ip)
    local_host_ip = socket.gethostbyname('localhost')
    if host_ip == local_host_ip or host_ip.startswith('127.'):
        return True
    else:
        return False


def get_host_ip() -> Union[str, None]:
    """
    >>> result = get_host_ip()
    >>> assert is_valid_ip_adress(result)
    """
    o_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    # noinspection PyBroadException
    try:
        # doesn't even have to be reachable
        o_socket.connect(('1.1.1.1', 1))
        s_ip = str(o_socket.getsockname()[0])  # type: Union[str, None]
    except Exception:           # pragma: no cover
        s_ip = None             # pragma: no cover
    finally:
        o_socket.close()
    return s_ip


def is_internet_connected(ip_adress: str = '1.1.1.1') -> bool:
    """
    >>> is_internet_connected()
    True
    >>> is_internet_connected(ip_adress='www.un-kno-wn.com')
    False
    """
    response = lib_ping.ping(target=ip_adress, times=1)
    return bool(response.reached)


def is_valid_ip_adress(address: str) -> bool:
    """
    check if it is valid IPV4 or IPV6 Adress
    >>> is_valid_ip_adress('1.1.1.1')
    True
    >>> is_valid_ip_adress('::1')
    True
    >>> is_valid_ip_adress('unknown')
    False
    """
    if is_valid_ipv4_address(address) or is_valid_ipv6_address(address):
        return True
    else:
        return False


def is_valid_ipv4_address(address: str) -> bool:
    """
    >>> is_valid_ipv4_address('1.1.1.1')
    True
    >>> is_valid_ipv4_address('1.1.1.')
    False
    >>> is_valid_ipv4_address('unknown')
    False
    """
    try:
        socket.inet_pton(socket.AF_INET, address)
    except AttributeError:                      # pragma: no cover      # no inet_pton here, sorry
        try:                                    # pragma: no cover
            socket.inet_aton(address)           # pragma: no cover
        except socket.error:                    # pragma: no cover
            return False                        # pragma: no cover
        return address.count('.') == 3          # pragma: no cover
    except socket.error:                        # not a valid address
        return False

    return True


def is_valid_ipv6_address(address: str) -> bool:
    """
    >>> is_valid_ipv6_address('::1')
    True
    >>> is_valid_ipv6_address('127.0.0.1')
    False
    >>> is_valid_ipv6_address('unknown')
    False
    """
    try:
        socket.inet_pton(socket.AF_INET6, address)
    except socket.error:  # not a valid address
        return False
    return True

你使用的是什么操作系统on@MZ我想要一个适用于所有操作系统的脚本,但首先是“linux”,然后是“windows”,也许你想检查ping函数()@MZ,正如我说的,我不想要ping(或者任何其他终端命令,如果存在的话)。但是如果我想使用ping,那么使用什么ip进行测试呢?192.168.1.1?这将获得默认网关的地址-应该是您的internet路由器-。试着ping一下。这里有一个很有用的函数,可以获得Linux上的默认网关。可能还值得一提的是,
requests.get()
的参数是一个URL,仅仅给它一个IP地址是无效的。我说的是“不是INTERNET”。我没有互联网,但我已连接到网络。这个答案对我来说还不够,因为我说过我希望python命令不是终端。使用
route print
时,我需要获得输出,然后根据正则表达式模式对其进行过滤。因为这个输出在其他设备上可能不同,我认为它无法工作。我认为您可能错过了答案的第二部分,它满足了您的“非互联网”要求。很抱歉,您对使用终端命令感到不舒服;在这方面获得更多的经验可能会对你将来有所帮助。哦,这是完全错误的。这与本地主机无关。127.0.0.1检查网络连接有什么用@RAMIN-RX7,如果您只有一个环回接口,那么您就没有连接到LAN!因此,如果无法ping默认网关,则无法确定是否连接到LAN,但可以检查本地IP地址是否与环回地址不同。如果主机适配器上没有IP地址,请确保未连接。