get_ip.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import re
  2. import logging
  3. import socket
  4. from urllib import request, error, parse
  5. # 匹配合法 IP 地址
  6. regex_ip = re.compile(
  7. r"\D*("
  8. + r"(?:1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[1-9])\."
  9. + r"(?:1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)\."
  10. + r"(?:1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)\."
  11. + r"(?:1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)"
  12. + r")\D*")
  13. # 增强鲁棒性,用多种方式获取 IP
  14. def get_ip():
  15. return (get_ip_by_ipip()
  16. or get_ip_by_httpbin()
  17. or get_ip_by_httpbin_direct_1()
  18. or get_ip_by_httpbin_direct_2() )
  19. # 这几个函数会在 DNS 遭受污染时失效
  20. def get_ip_by_ipip():
  21. url = 'http://myip.ipip.net/'
  22. try:
  23. resp = request.urlopen(url=url, timeout=10).read()
  24. return regex_ip.match(resp.decode("utf-8")).group(1)
  25. except Exception as e:
  26. logging.warning("get_ip_by_ipip FAILED, error: %s", str(e))
  27. return None
  28. def get_ip_by_httpbin():
  29. url = 'http://www.httpbin.org/ip'
  30. try:
  31. resp = request.urlopen(url=url, timeout=10).read()
  32. return regex_ip.match(resp.decode("utf-8")).group(1)
  33. except Exception as e:
  34. logging.warning("get_ip_by_httpbin FAILED, error: %s", str(e))
  35. return None
  36. # 这个函数可以在本地 DNS 遭受污染的时候获取到IP
  37. # 如需模拟DNS污染,可以在HOSTS文件里加入 127.0.0.1 www.httpbin.org
  38. def get_ip_by_httpbin_direct_1():
  39. url = 'http://52.5.182.176/ip'
  40. try:
  41. req = request.Request(url=url, method='GET', headers={'Host': 'www.httpbin.org'})
  42. resp = request.urlopen(req).read()
  43. return regex_ip.match(resp.decode("utf-8")).group(1)
  44. except Exception as e:
  45. logging.warning("get_ip_by_httpbin_direct_1 FAILED, error: %s", str(e))
  46. return None
  47. def get_ip_by_httpbin_direct_2():
  48. url = 'http://52.44.230.61/ip'
  49. try:
  50. req = request.Request(url=url, method='GET', headers={'Host': 'www.httpbin.org'})
  51. resp = request.urlopen(req).read()
  52. return regex_ip.match(resp.decode("utf-8")).group(1)
  53. except Exception as e:
  54. logging.warning("get_ip_by_httpbin_direct_2 FAILED, error: %s", str(e))
  55. return None
  56. # 测试
  57. if __name__ == '__main__':
  58. print(get_ip() )
  59. print(get_ip_by_ipip() )
  60. print(get_ip_by_httpbin() )
  61. print(get_ip_by_httpbin_direct_1() )