某域名背后的服务器都布置在国外,DNS服务器会将此域名解析到不固定的IP地址,其中某些IP地址在国内访问速度挺快,有些很慢,还有一些则根本没法访问。为提升访问的稳定性,我决定先找出访问速度最快的IP,而后修改hosts文件指向这个IP,省去DNS服务器的解析。
首先经过https://ping.chinaz.com/找出目标域名的所有IP地址,保存到txt文件中,每一个IP地址占一行(也能够使用逗号分割)。而后用python3的open读入文件,用ping3包的ping函数测试每一个IP地址的访问延迟,测试n次后求平均值。对于访问超时的IP地址,直接赋给它一个很长的时间,好比5000ms. 将IP地址及测试结果再写入另外一个文本文件。若从未使用过ping3,请先安装:pip install ping3
代码以下:
python
import ping3 fread=open(r"E:\PythonDevelop\IPList.txt",'r') fwrite=open(r"E:\PythonDevelop\IPTest.txt",'w') TargetIP=fread.readline() n=3 while TargetIP: TotalTime=0.0 for k in range(n): IPstrip=TargetIP.strip() PingTime=ping3.ping(IPstrip,timeout=1,unit='ms') if not PingTime: PingTime=5000.0 TotalTime=TotalTime+PingTime print(IPstrip+','+str(int(TotalTime/n))) fwrite.writelines(IPstrip+','+str(int(TotalTime/3))+'\n') TargetIP=fread.readline() fread.close() fwrite.close()
ping函数的说明以下:
ping(dest_addr: str, timeout: int = 4, unit: str = 's', src_addr: str = None, ttl: int = 64, seq: int = 0, size: int = 56, interface: str = None) -> float
Send one ping to destination address with the given timeout.
服务器
Args:
dest_addr: The destination address, can be an IP address or a domain name. Ex. "192.168.1.1"/"example.com"
timeout: Time to wait for a response, in seconds. Default is 4s, same as Windows CMD. (default 4)
unit: The unit of returned value. "s" for seconds, "ms" for milliseconds. (default "s")
src_addr: WINDOWS ONLY. The IP address to ping from. This is for multiple network interfaces. Ex. "192.168.1.20". (default None)
interface: LINUX ONLY. The gateway network interface to ping from. Ex. "wlan0". (default None)
ttl: The Time-To-Live of the outgoing packet. Default is 64, same as in Linux and macOS. (default 64)
seq: ICMP packet sequence, usually increases from 0 in the same process. (default 0)
size: The ICMP packet payload size in bytes. If the input of this is less than the bytes of a double format (usually 8), the size of ICMP packet payload is 8 bytes to hold a time. The max should be the router_MTU(Usually 1480) - IP_Header(20) - ICMP_Header(8). Default is 56, same as in macOS. (default 56)
less
Returns:
The delay in seconds/milliseconds or None on timeout.
dom
Raises:
PingError: Any PingError will raise again if `ping3.EXCEPTIONS` is True.
函数