www.weide1946.com获取本地ip和获取公网ip

2019-05-07 02:30 来源:未知
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())
版权声明:本文由韦德娱乐1946_韦德娱乐1946网页版|韦德国际1946官网发布于网络编程,转载请注明出处:www.weide1946.com获取本地ip和获取公网ip