Get the IP Python x_forwarded_for = request. META.get('HTTP_X_FORWARDED_FOR') Determine whether to use a proxy if x_forwarde
Get the city according to IP
Published: 2025-07-21 (a year ago)
Python

Get the IP

if x_forwarded_for:

Python Copy
x_forwarded_for = request. META.get('HTTP_X_FORWARDED_FOR') # Determine whether to use a proxy
ip = x_forwarded_for.split(',')[0] # Use a proxy to get the real IP
else:
ip = request. META.get('REMOTE_ADDR') # No proxy is used to get the IP

print(ip)

获取城市

Python Copy
import requests
import re

headers = {
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
                  "AppleWebKit/537.36 (KHTML, like Gecko) "
                  "Chrome/98.0.4758.102 Safari/537.36"
}


def get_city(ip: str) -> dict:
    """
    合法 ip 返回国家,城市,和运营商
    查不到运营商的就返回 国家,城市
    内网 ip返回 内网
    :param ip:
    :return:
    """
    # 构造返回的字典
    response = {
        "country": '',
        "city": '',
    }
    # 判断是否是内网 ip
    if ip.startswith('127') or ip.startswith('192.') or ip.startswith('10.'):
        response['msg'] = '内网'
        return response
    url = f'https://ip.cn/ip/{ip}.html'
    res = requests.get(url=url, headers=headers)
    result: str = re.findall(r'<div id="tab0_address">(.*?)</div>', res.text)[0].strip()

    res_list = result.split('  ')
    response['country'] = res_list[0]
    city_or_operator = res_list[1]
    city = city_or_operator.split(' ')
    response['city'] = city[0] + '-' + city[1]
    if len(city) == 3:
        response['operator'] = city[2]
    return response


if __name__ == '__main__':
    print(get_city('127.0.0.1'))
    print(get_city('192.168.44.33'))
    print(get_city('117.136.24.38'))
    print(get_city('218.76.35.2'))
    print(get_city('110.53.253.137'))
    print(get_city('36.99.136.139'))
    print(get_city('106.13.185.190'))
    print(get_city('42.194.130.81'))