app.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import ipdb, ipaddress
  2. from flask import Flask, request, render_template, jsonify
  3. from socket import gethostbyname
  4. db = ipdb.BaseStation("qqwry.ipdb")
  5. app = Flask(__name__)
  6. def iplocated(ip):
  7. city = db.find(ip, "CN")
  8. return ip + " @" + city[0] + city[1] + city[2] + city[3] + "\n"
  9. def getip():
  10. ip = request.remote_addr
  11. try:
  12. _ip = request.headers["X-Real-IP"]
  13. if _ip is not None:
  14. ip = _ip
  15. except Exception as e:
  16. print(e)
  17. return ip
  18. def is_Mozilla():
  19. # Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36
  20. ua = request.headers["User-Agent"]
  21. if (ua.find("Mozilla") != -1):
  22. return True
  23. else:
  24. return False
  25. @app.route("/")
  26. def hello():
  27. ip = getip()
  28. if is_Mozilla():
  29. return ip + render_template('hello.html') + "\n\n" + request.headers["User-Agent"]
  30. else:
  31. return ip
  32. @app.route("/ip")
  33. @app.route("/ip/")
  34. @app.route("/ip/<ipaddr>")
  35. def show_ip(ipaddr=None):
  36. # ip 地址为空获得浏览器客户端IP
  37. if ipaddr is None:
  38. ip = getip()
  39. ipaddr = iplocated(ip)
  40. if is_Mozilla():
  41. return render_template('hello.html', ip=ip, ipaddr=ipaddr)
  42. else:
  43. return ip
  44. else:
  45. ip = ipaddr
  46. # ip地址 从纯真IP数据库 搜索城市定位
  47. try:
  48. ipaddress.ip_address(ip).is_global
  49. ipaddr = iplocated(ip)
  50. except:
  51. try:
  52. ip = gethostbyname(ip) # 域名反解析得到的IP
  53. ipaddr = iplocated(ip)
  54. except Exception as e:
  55. print(e)
  56. return ipaddr
  57. if __name__ == '__main__':
  58. app.run(host='0.0.0.0', debug=True)
  59. # export FLASK_ENV=development # 调试模式: 修改代码不用重启服务
  60. # flask run --host=0.0.0.0 # 监听所有公开的 IP