Windows下快速判断能不能ping通

原理如下:

ping 10.10.10.4 -n 1 -w 500

参数-n 1只ping一次,参数-w 500设置500毫秒超时返回。

封装的Python代码如下:

def is_pingable(ip: str = "10.10.10.4") -> bool:
    import subprocess
    cmd = f"ping {ip}  -n 1 -w 500"
    cp = subprocess.run(cmd, shell=True, capture_output=True)
    return cp.returncode == 0

这里有个需要注意的细节,如果写一个死循环不停得检测,有可能会出现明明ping不通但是返回ping通的情况,怀疑是间隔太短,两次的ping互相影响造成的,加一个delay就正常了。

2023年9月8日补充

命令中 -w 参数也不是很精确,写了程序简单测试了下:

import time

def is_pingable(ip: str = "10.10.10.4", time_out: int = 500) -> bool:
    import subprocess

    cmd = f"ping {ip}  -n 1 -w {time_out}"
    cp = subprocess.run(cmd, shell=True, capture_output=True)
    return cp.returncode == 0

if __name__ == "__main__":
    for t in range(100, 5000, 100):
        start_time = time.perf_counter()
        is_pingable(time_out=t)
        end_time = time.perf_counter()
        print(f"Time taken for {t}ms: {end_time - start_time:0.4f} seconds")
        time.sleep(0.2)

测试结果如下:

Time taken for 100ms: 0.4764 seconds
Time taken for 200ms: 0.2852 seconds
Time taken for 300ms: 0.3078 seconds
Time taken for 400ms: 0.3017 seconds
Time taken for 500ms: 0.2977 seconds
Time taken for 600ms: 0.3016 seconds
Time taken for 700ms: 0.2990 seconds
Time taken for 800ms: 0.3023 seconds
Time taken for 900ms: 0.2977 seconds
Time taken for 1000ms: 0.7889 seconds
Time taken for 1100ms: 0.7998 seconds
Time taken for 1200ms: 0.8053 seconds
Time taken for 1300ms: 0.8042 seconds
Time taken for 1400ms: 0.7968 seconds
Time taken for 1500ms: 1.2974 seconds
Time taken for 1600ms: 1.3029 seconds
Time taken for 1700ms: 1.2865 seconds
Time taken for 1800ms: 1.3034 seconds
Time taken for 1900ms: 1.3021 seconds
Time taken for 2000ms: 1.8020 seconds
Time taken for 2100ms: 1.8007 seconds
Time taken for 2200ms: 1.8015 seconds
Time taken for 2300ms: 1.7895 seconds
Time taken for 2400ms: 1.8046 seconds
Time taken for 2500ms: 2.2997 seconds
Time taken for 2600ms: 2.2999 seconds
Time taken for 2700ms: 2.2995 seconds
Time taken for 2800ms: 2.3054 seconds
Time taken for 2900ms: 2.2848 seconds
Time taken for 3000ms: 2.8038 seconds
Time taken for 3100ms: 2.7982 seconds
Time taken for 3200ms: 2.7974 seconds
Time taken for 3300ms: 2.7996 seconds
Time taken for 3400ms: 2.8044 seconds
Time taken for 3500ms: 3.2954 seconds
Time taken for 3600ms: 3.3056 seconds
Time taken for 3700ms: 3.2883 seconds
Time taken for 3800ms: 3.3044 seconds
Time taken for 3900ms: 3.3031 seconds
Time taken for 4000ms: 3.7972 seconds
Time taken for 4100ms: 3.8004 seconds
Time taken for 4200ms: 3.7973 seconds
Time taken for 4300ms: 3.7856 seconds
Time taken for 4400ms: 3.8062 seconds
Time taken for 4500ms: 4.3079 seconds
Time taken for 4600ms: 4.2993 seconds
Time taken for 4700ms: 4.2877 seconds
Time taken for 4800ms: 4.3017 seconds
Time taken for 4900ms: 4.2972 seconds

根据我的测试,这个参数设置到200差不多就是极限了。(Windows 10 i7-1165G7 )

Leave a Comment

Back to Top