Python获取本机所有IP地址 作者:马育民 • 2023-08-20 15:57 • 阅读:10106 ``` import socket # 查看当前主机名 #print('当前主机名称为 : ' + socket.gethostname()) # 根据主机名称获取当前IP #print('当前主机的IP为: ' + socket.gethostbyname(socket.gethostname())) # Mac下上述方法均返回127.0.0.1 # 通过使用socket中的getaddrinfo中的函数获取真真的IP # 下方代码为获取当前主机IPV4 和IPV6的所有IP地址(所有系统均通用) def get_local_ip(): addrs = socket.getaddrinfo(socket.gethostname(), None) ips = [item[4][0] for item in addrs ] return tuple(ips) def get_local_ipv4(): addrs = socket.getaddrinfo(socket.gethostname(),None) # for item in addrs: # if item[0] == socket.AddressFamily.AF_INET: # print('当前主机IPV4地址为:' + item[4][0]) ips = [item[4][0] for item in addrs if item[0] == socket.AddressFamily.AF_INET ] return tuple(ips) if __name__ == '__main__': # ips = get_local_ipv4() ips = get_local_ip() print(ips) ``` 参考: https://cloud.tencent.com/developer/article/1571753 原文出处:https://malaoshi.top/show_1IX65ELDjVMt.html