目录
方法一
方法二
方法三
方法一
#获取本机IP地址def get_local_ip():# s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)# s.connect(('8.8.8.8', 80))# ip = s.getsockname()[0]# s.close()ip = socket.gethostbyname(socket.gethostname())return ip
运行结果:
D:\Python3.8.6\python.exe D:/PythonWorkSpace/someip/Common/get_IP_adress.py192.168.42.44Process finished with exit code 0
方法二
#获取公网IP地址def get_public_ip():response = requests.get("http://httpbin.org/ip")data = response.json()ip = data['origin']return ip
运行结果:
D:\Python3.8.6\python.exe D:/PythonWorkSpace/someip/Common/get_IP_adress.py223.76.212.244Process finished with exit code 0
方法三
# 获取本机所有 IP 地址def get_all_ip():hostname = socket.gethostname()ip_list = []# 获取IP地址信息addr_infos = socket.getaddrinfo(hostname, None)for addr in addr_infos:ip_list.append(addr[4][0])# print(ip_list)return ip_list
运行结果:
D:\Python3.8.6\python.exe D:/PythonWorkSpace/someip/Common/get_IP_adress.pyfe80::f439:ac0:9050:c9ffe80::1d73:c1cf:c1ca:6d0dfe80::9d23:6620:a01:aa33fe80::856d:dbe3:ada3:a32a192.168.42.44172.29.11.5192.168.114.1192.168.64.1Process finished with exit code 0