AutoFramework/Base/Class/Network.py

49 lines
1.4 KiB
Python
Raw Normal View History

2022-06-27 23:11:22 +08:00
import re,chardet,platform,subprocess,socket
def ping(host='', version=None):
def sh(cmd='', timeout=None):
try:
2022-06-28 15:13:05 +08:00
result = subprocess.run(
cmd, shell=True,
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, timeout=timeout)
2022-06-27 23:11:22 +08:00
if result.stdout:
return result.stdout.decode(chardet.detect(result.stdout)["encoding"] or 'UTF-8')
return ''
except:
return ''
match version:
case 4 | 6:
versionCh = ' -' + str(version)
case _:
versionCh = ''
match platform.system():
case 'Windows':
result = sh('chcp 65001 && ping -n 1' + versionCh + ' ' + host, timeout=5)
case _:
result = sh('ping -c 1' + versionCh + ' ' + host, timeout=5)
delayList = re.findall('([0-9.]+)[\s]?ms*',result)
if len(delayList) == 0:
return False
else:
return round(float(delayList[0]),1)
def resolve(host=''):
try:
addrLst = socket.getaddrinfo(host, None)
except:
addrLst = []
inetLst = []
for value in addrLst:
match value[0]:
case socket.AddressFamily.AF_INET6:
t = 'IPv6'
case _:
t = 'IPv4'
inetLst.append([t, value[4][0]])
return inetLst
if __name__ == '__main__':
# Example.
print('PING:',ping('www.baidu.com'),'ms')
# Example.
print(resolve('dns.google'))