系统网络连接?无需联系 [Windows,MacOS,Ubuntu]

System network connectivity? WITHOUT reaching out [Windows, MacOS, Ubuntu]

我知道

ping -c 1 8.8.8.8

干净便携的方式怎么样? 我认为最好的方法是检查 syslog 的最后一个请求或询问网络管理员,但除了 Android (http://developer.android.com/reference/android/net/ConnectivityManager.html) 我找不到任何东西......

我正在使用 Python 但此代码不存在...

import sys
sys.getnetworkstatus() # True when recent succesful connection went through

有什么指点吗?

以下程序会告诉您是否已连接到 Internet。

import netifaces
def is_connected_to_an_internet():
    ifaces = netifaces.interfaces()
    for iface in ifaces:
        addrs = netifaces.ifaddresses(iface)
        for addr in addrs.get(netifaces.AF_INET, []):
            if addr['addr'].startswith('127'): continue
            return True
        for addr in addrs.get(netifaces.AF_INET6, []):
            if addr['addr'] == '::1': continue
            if addr['addr'].lower().startswith('fe80'): continue
            return True
    return False

参考:https://pypi.python.org/pypi/netifaces

"Is the system online" 是一个严重未指定的问题。您真正想要答案的问题是:

Can I reach a remote service on a remote host right now?

只有一个有效答案:

Try it and see.

你可以查看系统配置的任何方面,接口是否正常,你是否有一个有效的 IP 地址,你是否通过一些代理连接,NAT 盒子是否正在运行,是远程服务 运行,是一些进入远程服务的路径拥塞和丢弃数据包,等等。所有这些以及更多只会产生您真正寻找的答案的近似值。

即使您在一秒钟前已经成功联系到您想要的服务,这告诉您关于您是否可以联系它现在的信息远远少于您想要的。