File size: 16,742 Bytes
c2ddfaf 7b7f906 c2ddfaf 2570377 c2ddfaf 7b7f906 c2ddfaf 2a43f18 c2ddfaf 2a43f18 c2ddfaf 2a43f18 c2ddfaf 2a43f18 c2ddfaf 2a43f18 c2ddfaf 2a43f18 c2ddfaf 2a43f18 c2ddfaf 57152db c2ddfaf 57152db c2ddfaf 57152db c2ddfaf 7b7f906 c2ddfaf 2570377 c2ddfaf 2570377 c2ddfaf 44af558 7b7f906 44af558 7b7f906 3fefe3f 7b7f906 c2ddfaf 57152db c2ddfaf ce733c9 7b7f906 ce733c9 160f5a5 7b7f906 ce733c9 7b7f906 ce733c9 7b7f906 ce733c9 160f5a5 7b7f906 ce733c9 7b7f906 ce733c9 7b7f906 2570377 c2ddfaf 44af558 7b7f906 44af558 57152db c2ddfaf 2570377 c2ddfaf | 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 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 | import ipaddress
import re
import maxminddb
from fastapi import FastAPI, Request
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse
import json
import datetime
import logging
import sys
import os
import httpx
from logging.handlers import RotatingFileHandler
LOG_FILE = os.path.join('/code', 'ip_query.log')
try:
formatter = logging.Formatter('%(message)s')
log_handler = RotatingFileHandler(
LOG_FILE,
maxBytes=10*1024*1024,
backupCount=5,
encoding='utf-8'
)
log_handler.setFormatter(formatter)
logger = logging.getLogger('ip_query')
logger.setLevel(logging.INFO)
logger.addHandler(log_handler)
startup_log = {
"时间": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"事件": "系统启动",
"状态": "成功"
}
logger.info(json.dumps(startup_log, ensure_ascii=False))
except Exception as e:
print(f"日志初始化失败: {e}")
sys.exit(1)
city_reader = maxminddb.open_database('GeoLite2-City.mmdb')
asn_reader = maxminddb.open_database('GeoLite2-ASN.mmdb')
cn_reader = maxminddb.open_database('GeoCN.mmdb')
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
FULL_DIVISION_FILE = os.path.join(BASE_DIR, 'full.txt')
SHORT_DIVISION_FILE = os.path.join(BASE_DIR, 'short.txt')
lang = ["zh-CN", "en"]
asn_map = {
9812: "东方有线",
9389: "中国长城",
17962: "天威视讯",
17429: "歌华有线",
7497: "科技网",
24139: "华数",
9801: "中关村",
4538: "教育网",
24151: "CNNIC",
38019: "中国移动", 139080: "中国移动", 9808: "中国移动", 24400: "中国移动", 134810: "中国移动", 24547: "中国移动",
56040: "中国移动", 56041: "中国移动", 56042: "中国移动", 56044: "中国移动", 132525: "中国移动", 56046: "中国移动",
56047: "中国移动", 56048: "中国移动", 59257: "中国移动", 24444: "中国移动",
24445: "中国移动", 137872: "中国移动", 9231: "中国移动", 58453: "中国移动",
4134: "中国电信", 4812: "中国电信", 23724: "中国电信", 136188: "中国电信", 137693: "中国电信", 17638: "中国电信",
140553: "中国电信", 4847: "中国电信", 140061: "中国电信", 136195: "中国电信", 17799: "中国电信", 139018: "中国电信",
134764: "中国电信", 4837: "中国联通", 4808: "中国联通", 134542: "中国联通", 134543: "中国联通",
59019: "金山云",
135377: "优刻云",
45062: "网易云",
37963: "阿里云", 45102: "阿里云国际",
45090: "腾讯云", 132203: "腾讯云国际",
55967: "百度云", 38365: "百度云",
58519: "华为云", 55990: "华为云", 136907: "华为云",
4609: "澳門電訊",
13335: "Cloudflare",
55960: "亚马逊云", 14618: "亚马逊云", 16509: "亚马逊云",
15169: "谷歌云", 396982: "谷歌云", 36492: "谷歌云",
}
def load_division_map(path, separator):
result = {}
with open(path, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
if not line:
continue
parts = line.split(separator, 1)
if len(parts) != 2:
continue
code, name = parts
result[int(code.strip())] = name.strip()
return result
division_full = load_division_map(FULL_DIVISION_FILE, '\t')
division_short = load_division_map(SHORT_DIVISION_FILE, ' ')
def get_as_info(number):
r = asn_map.get(number)
if r:
return r
def get_des(d):
for i in lang:
if i in d['names']:
return d['names'][i]
return d['names']['en']
def get_country(d):
r = get_des(d)
if r in ["香港", "澳门", "台湾"]:
return "中国" + r
return r
def province_match(s):
arr = ['内蒙古', '黑龙江', '河北', '山西', '吉林', '辽宁', '江苏', '浙江', '安徽', '福建', '江西', '山东', '河南', '湖北', '湖南', '广东', '海南', '四川', '贵州', '云南', '陕西', '甘肃', '青海', '广西', '西藏', '宁夏', '新疆', '北京', '天津', '上海', '重庆']
for i in arr:
if i in s:
return i
return ''
def de_duplicate(regions):
regions = filter(bool, regions)
ret = []
[ret.append(i) for i in regions if i not in ret]
return ret
def get_addr(ip, mask):
network = ipaddress.ip_network(f"{ip}/{mask}", strict=False)
first_ip = network.network_address
return f"{first_ip}/{mask}"
def resolve_division(code):
if not code:
return [], []
code = int(code)
province_code = (code // 10000) * 10000
city_code = (code // 100) * 100
full = []
short = []
province_full = division_full.get(province_code)
province_short = division_short.get(province_code)
if province_full:
full.append(province_full)
if province_short:
short.append(province_short)
if city_code != province_code:
city_full = division_full.get(city_code)
city_short = division_short.get(city_code)
if city_full:
full.append(city_full)
if city_short:
short.append(city_short)
if code != city_code and code != province_code:
district_full = division_full.get(code)
district_short = division_short.get(code)
if district_full:
full.append(district_full)
if district_short:
short.append(district_short)
if len(full) >= 2 and full[0] == full[1]:
full = full[1:]
if len(short) >= 2 and short[0] == short[1]:
short = short[1:]
return de_duplicate(full), de_duplicate(short)
def get_maxmind(ip: str):
ret = {"ip": ip}
asn_info = asn_reader.get(ip)
if asn_info:
as_ = {"number": asn_info["autonomous_system_number"], "name": asn_info["autonomous_system_organization"]}
info = get_as_info(as_["number"])
if info:
as_["info"] = info
ret["as"] = as_
city_info, prefix = city_reader.get_with_prefix_len(ip)
ret["addr"] = get_addr(ip, prefix)
if not city_info:
return ret
if "location" in city_info:
location = city_info["location"]
ret["location"] = {
"latitude": location.get("latitude"),
"longitude": location.get("longitude")
}
if "country" in city_info:
country_code = city_info["country"]["iso_code"]
country_name = get_country(city_info["country"])
ret["country"] = {"code": country_code, "name": country_name}
if "registered_country" in city_info:
registered_country_code = city_info["registered_country"]["iso_code"]
ret["registered_country"] = {"code": registered_country_code, "name": get_country(city_info["registered_country"])}
regions = [get_des(i) for i in city_info.get('subdivisions', [])]
if "city" in city_info:
c = get_des(city_info["city"])
if (not regions or c not in regions[-1]) and c not in country_name:
regions.append(c)
regions = de_duplicate(regions)
if regions:
ret["regions"] = regions
return ret
def get_cn(ip: str, info=None):
if info is None:
info = {}
ret, prefix = cn_reader.get_with_prefix_len(ip)
if not ret:
return
info["addr"] = get_addr(ip, prefix)
division_code = ret.get("division_code")
regions, regions_short = resolve_division(division_code)
if regions:
info["regions"] = regions
if regions_short:
info["regions_short"] = regions_short
isp = ret.get("isp")
if isp:
if "as" not in info:
info["as"] = {}
info["as"]["info"] = isp
net_type = ret.get("type") or ret.get("net")
if net_type:
info["type"] = net_type
return ret
async def get_ip_info(ip):
info = get_maxmind(ip)
is_cn = "country" in info and info["country"]["code"] == "CN" and ("registered_country" not in info or info["registered_country"]["code"] == "CN")
if is_cn:
get_cn(ip, info)
# 中国 IP 优先使用美团数据覆盖经纬度和地区,失败则保留本地数据库结果
try:
mt = await get_meituan_location(ip)
if "error" not in mt:
loc = mt.get("location", {})
if loc.get("lat") and loc.get("lng"):
info["location"] = {
"latitude": loc["lat"],
"longitude": loc["lng"]
}
regions = de_duplicate([loc.get("province", ""), loc.get("city", ""), loc.get("district", "")])
if regions:
info["regions"] = regions
info["regions_short"] = de_duplicate([
province_match(loc.get("province", "")),
loc.get("city", "").replace('市', ''),
loc.get("district", "")
])
if loc.get("detail"):
info["detail"] = loc["detail"]
if loc.get("areaName"):
info["areaName"] = loc["areaName"]
except Exception:
pass # 美团接口失败,保留 GeoCN 数据
return info
def is_reserved_ip(ip: str) -> bool:
try:
octets = list(map(int, ip.split(".")))
if len(octets) != 4:
return False
if octets[0] == 10: return True
if octets[0] == 172 and 16 <= octets[1] <= 31: return True
if octets[0] == 192 and octets[1] == 168: return True
if octets[0] == 169 and octets[1] == 254: return True
if octets[0] == 127: return True
if octets[0] == 0: return True
if octets[0] == 100 and 64 <= octets[1] <= 127: return True
if octets[0] >= 224: return True
except Exception:
return False
return False
async def get_meituan_location(ip: str):
async with httpx.AsyncClient(timeout=10) as client:
loc_resp = await client.get(f"https://apimobile.meituan.com/locate/v2/ip/loc?rgeo=true&ip={ip}")
loc_data = loc_resp.json()
if not loc_data.get("data"):
return {"ip": ip, "error": "无法获取IP地理位置信息"}
lat = loc_data["data"].get("lat")
lng = loc_data["data"].get("lng")
rgeo = loc_data["data"].get("rgeo", {})
result = {
"ip": ip,
"location": {
"country": rgeo.get("country", ""),
"province": rgeo.get("province", ""),
"city": rgeo.get("city", ""),
"district": rgeo.get("district", ""),
"lat": lat,
"lng": lng
}
}
if lat and lng:
try:
detail_resp = await client.get(f"https://apimobile.meituan.com/group/v1/city/latlng/{lat},{lng}?tag=0")
detail_data = detail_resp.json()
detail = detail_data.get("data", {})
result["location"]["detail"] = detail.get("detail", "")
if detail.get("areaName"):
result["location"]["areaName"] = detail["areaName"]
except Exception:
result["location"]["detail"] = ""
return result
def query():
while True:
try:
ip = input('IP: \t').strip()
info = get_ip_info(ip)
print(f"网段:\t{info['addr']}")
if "location" in info:
print(f"经纬度:\t{info['location']['latitude']}, {info['location']['longitude']}")
if "as" in info:
print(f"ISP:\t", end=' ')
if "info" in info["as"]:
print(info["as"]["info"], end=' ')
else:
print(info["as"]["name"], end=' ')
if "type" in info:
print(f"({info['type']})", end=' ')
print(f"ASN{info['as']['number']}", end=' ')
print(info['as']["name"])
if "registered_country" in info and ("country" not in info or info["country"]["code"] != info["registered_country"]["code"]):
print(f"注册地:\t{info['registered_country']['name']}")
if "country" in info:
print(f"使用地:\t{info['country']['name']}")
if "regions" in info:
print(f"位置: \t{' '.join(info['regions'])}")
except Exception as e:
print(e)
raise e
finally:
print("\n")
app = FastAPI()
# 前端页面
@app.get("/")
async def index():
return FileResponse("static/index.html")
# API 端点
@app.get("/api/")
async def api(request: Request, ip: str = None):
# 优先获取 Cloudflare 传递的真实 IP
client_ip = (
request.headers.get("cf-connecting-ip") or
request.headers.get("x-real-ip") or
request.headers.get("x-forwarded-for") or
request.client.host
)
if client_ip and ',' in client_ip:
client_ip = client_ip.split(',')[0].strip()
query_ip = ip.strip() if ip else client_ip
result = await get_ip_info(query_ip)
log_data = {
"时间": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"访问IP": client_ip,
"查询IP": query_ip,
"请求头": dict(request.headers),
"查询结果": result
}
logger.info(json.dumps(log_data, ensure_ascii=False))
return result
# 美团 API 精确定位端点(必须在 /api/{ip} 之前定义)
@app.get("/api/locate/")
async def locate_api(request: Request, ip: str = None):
client_ip = (
request.headers.get("cf-connecting-ip") or
request.headers.get("x-real-ip") or
request.headers.get("x-forwarded-for") or
request.client.host
)
if client_ip and ',' in client_ip:
client_ip = client_ip.split(',')[0].strip()
query_ip = ip.strip() if ip else client_ip
try:
addr = ipaddress.ip_address(query_ip)
except ValueError:
return {"error": "无效的IP地址格式"}
if addr.is_private or addr.is_reserved or addr.is_loopback:
return {"error": "不支持查询内网IP或保留地址"}
try:
result = await get_meituan_location(query_ip)
except Exception as e:
result = {"ip": query_ip, "error": str(e)}
log_data = {
"时间": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"访问IP": client_ip,
"查询IP": query_ip,
"类型": "美团定位",
"查询结果": result
}
logger.info(json.dumps(log_data, ensure_ascii=False))
return result
@app.get("/api/locate/{ip}")
async def locate_path_api(request: Request, ip: str):
client_ip = (
request.headers.get("cf-connecting-ip") or
request.headers.get("x-real-ip") or
request.headers.get("x-forwarded-for") or
request.client.host
)
if client_ip and ',' in client_ip:
client_ip = client_ip.split(',')[0].strip()
try:
addr = ipaddress.ip_address(ip)
except ValueError:
return {"error": "无效的IP地址格式"}
if addr.is_private or addr.is_reserved or addr.is_loopback:
return {"error": "不支持查询内网IP或保留地址"}
try:
result = await get_meituan_location(ip)
except Exception as e:
result = {"ip": ip, "error": str(e)}
log_data = {
"时间": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"访问IP": client_ip,
"查询IP": ip,
"类型": "美团定位",
"查询结果": result
}
logger.info(json.dumps(log_data, ensure_ascii=False))
return result
@app.get("/api/{ip}")
async def path_api(request: Request, ip: str):
client_ip = (
request.headers.get("cf-connecting-ip") or
request.headers.get("x-real-ip") or
request.headers.get("x-forwarded-for") or
request.client.host
)
if client_ip and ',' in client_ip:
client_ip = client_ip.split(',')[0].strip()
result = await get_ip_info(ip)
log_data = {
"时间": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"访问IP": client_ip,
"查询IP": ip,
"请求头": dict(request.headers),
"查询结果": result
}
logger.info(json.dumps(log_data, ensure_ascii=False))
return result
# 静态文件服务
app.mount("/static", StaticFiles(directory="static"), name="static")
if __name__ == '__main__':
query()
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8080, server_header=False, proxy_headers=True)
|