获取本地ip和获取公网ip

时间:2023-03-09 16:10:10
获取本地ip和获取公网ip
import socket

def get_local_ip():
'''
获取本地ip地址
:return:
'''
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect(('8.8.8.8', 80))
local_ip = s.getsockname()[0]
except:
local_ip.close()
return local_ip print(get_local_ip())
import requests, chardet, re

def get_net_ip():
'''
获取公网ip地址
:return:
'''
html = requests.get('http://2018.ip138.com/ic.asp')
html.encoding = chardet.detect(html.content)['encoding']
try:
match_obj = re.findall(r'您的IP是:\[(.*?)\] 来自', html.text)
network_ip = match_obj[0].strip()
return network_ip
except:
print('解析出错!') print(get_net_ip())