目录
方法一
方法二
方法三
方法一
#获取本机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.py
192.168.42.44
Process 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
运行结果:文章来源:https://www.toymoban.com/news/detail-738082.html
D:\Python3.8.6\python.exe D:/PythonWorkSpace/someip/Common/get_IP_adress.py
223.76.212.244
Process 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
运行结果:文章来源地址https://www.toymoban.com/news/detail-738082.html
D:\Python3.8.6\python.exe D:/PythonWorkSpace/someip/Common/get_IP_adress.py
fe80::f439:ac0:9050:c9f
fe80::1d73:c1cf:c1ca:6d0d
fe80::9d23:6620:a01:aa33
fe80::856d:dbe3:ada3:a32a
192.168.42.44
172.29.11.5
192.168.114.1
192.168.64.1
Process finished with exit code 0
到了这里,关于Python:获取ip地址的三种方法的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!