import re,chardet,platform,subprocess,socket def ping(host='', version=None): def sh(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: 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'))