69 lines
2.0 KiB
Python
69 lines
2.0 KiB
Python
import chardet
|
|
import platform
|
|
import re
|
|
import socket
|
|
import subprocess
|
|
|
|
|
|
def ping(host='', version=None):
|
|
def shell_exec(cmd='', timeout=None):
|
|
try:
|
|
result = subprocess.run(
|
|
cmd, shell=True,
|
|
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, timeout=timeout)
|
|
if result.stdout:
|
|
return result.stdout.decode(chardet.detect(result.stdout)["encoding"] or 'UTF-8')
|
|
return ''
|
|
except Exception:
|
|
return ''
|
|
|
|
match version:
|
|
case 4 | 6:
|
|
version_ch = '\x20-' + str(version)
|
|
case _:
|
|
version_ch = ''
|
|
match platform.system():
|
|
case 'Windows':
|
|
result = shell_exec('chcp 65001 && ping -n 1' + version_ch + ' ' + host, timeout=5)
|
|
case _:
|
|
result = shell_exec('ping -c 1' + version_ch + ' ' + host, timeout=5)
|
|
delay = re.findall('([0-9.]+)[\s]?ms*', result)
|
|
if len(delay) == 0:
|
|
return False
|
|
else:
|
|
return round(float(delay[0]), 1)
|
|
|
|
|
|
def resolve(host='', version=None):
|
|
result = []
|
|
lst = []
|
|
try:
|
|
lst = socket.getaddrinfo(host, None)
|
|
except:
|
|
pass
|
|
for value in lst:
|
|
address = value[4][0]
|
|
match value[0]:
|
|
case socket.AddressFamily.AF_INET6:
|
|
if version == 6 or version is None:
|
|
result.append(address)
|
|
case _:
|
|
if version == 4 or version is None:
|
|
result.append(address)
|
|
return result
|
|
|
|
|
|
if __name__ == '__main__':
|
|
# Example. PING IPv4 Test.
|
|
print('PING:', ping('www.taobao.com', version=4), 'ms')
|
|
# Example. PING IPv6 Test.
|
|
print('PING:', ping('www.taobao.com', version=6), 'ms')
|
|
# Example. PING Auto Test.
|
|
print('PING:', ping('www.taobao.com'), 'ms')
|
|
# Example. Resolve IPv4-Only Host.
|
|
print(resolve('www.taobao.com', version=4))
|
|
# Example. Resolve IPv6-Only Host.
|
|
print(resolve('www.taobao.com', version=6))
|
|
# Example. Resolve IPv4/6 Host.
|
|
print(resolve('www.taobao.com'))
|