File size: 2,126 Bytes
551658a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import logging
from typing import Dict, Optional

logger = logging.getLogger(__name__)


class IPLocationService:
    """IP地理位置解析服务(降级版本)"""
    
    def __init__(self):
        pass
    
    def get_location(self, ip_address: str) -> Dict[str, Optional[str]]:
        """
        根据IP地址获取地理位置信息
        
        Returns:
            {
                "country": "国家",
                "region": "地区/省份",
                "city": "城市",
                "latitude": "纬度",
                "longitude": "经度"
            }
        """
        try:
            # 如果是本地IP,返回默认值
            if self._is_private_ip(ip_address):
                return {
                    "country": "中国",
                    "region": "本地",
                    "city": "本地",
                    "latitude": "39.9042",
                    "longitude": "116.4074"
                }
            
            # 降级:返回默认位置
            return self._get_default_location()
                
        except Exception as e:
            logger.error(f"IP地理位置解析异常: {ip_address}, 错误: {str(e)}")
            return self._get_default_location()
    
    def _is_private_ip(self, ip: str) -> bool:
        """检查是否为私有IP地址"""
        if ip.startswith("127.") or ip.startswith("192.168.") or ip.startswith("10."):
            return True
        if ip.startswith("172."):
            parts = ip.split(".")
            if len(parts) >= 2:
                try:
                    second_octet = int(parts[1])
                    if 16 <= second_octet <= 31:
                        return True
                except ValueError:
                    pass
        return False
    
    def _get_default_location(self) -> Dict[str, Optional[str]]:
        """返回默认位置"""
        return {
            "country": None,
            "region": None,
            "city": None,
            "latitude": None,
            "longitude": None
        }


# 全局实例
ip_location_service = IPLocationService()