utility.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. """
  2. Utility functions needed by various modules.
  3. """
  4. import struct
  5. import requests
  6. import re
  7. import logging
  8. pack4bytes_be = struct.Struct(">BBBB").pack
  9. split_dot = re.compile("\.").split
  10. pattern_ipresponse = re.compile("(<div class=\"title\"><strong>\d+\.\d+\.\d+\.\d+</strong></div>)")
  11. pattern_ip = re.compile("\d+\.\d+\.\d+\.\d+")
  12. logger = logging.getLogger("pra_framework")
  13. def int_to_ip_str(ip_int):
  14. """
  15. Convert an integer to an IP string
  16. return -- an IP address like "1.2.3.4"
  17. """
  18. return "%d.%d.%d.%d" % ((ip_int >> 24), (ip_int >> 16) & 255, (ip_int >> 8) & 255, ip_int & 255)
  19. def int_to_ip_bytes(ip_int):
  20. """
  21. Convert an integer to an IP string (byte representation)
  22. return -- an IP address like b"\x00\x01\x02\x03"
  23. """
  24. return pack4bytes_be((ip_int >> 24), (ip_int >> 16) & 255, (ip_int >> 8) & 255, ip_int & 255)
  25. def ip_str_to_int(ip_str):
  26. a,b,c,d = split_dot(ip_str)
  27. return (int(a) << 24) | (int(b) << 16) | (int(c) << 8) | int(d)
  28. def ip_str_to_bytes(ip_str):
  29. ip_digits = ip_str.split(".")
  30. return pack4bytes_be(int(ip_digits[0]), int(ip_digits[1]), int(ip_digits[2]), int(ip_digits[3]))
  31. def get_external_ip():
  32. """
  33. Get the IP address as seen from the internet.
  34. return -- IP address as string or None
  35. """
  36. response = requests.get("http://www.wieistmeineip.de/")
  37. matches = pattern_ipresponse.search(response.text)
  38. if matches is None:
  39. raise Exception("no IP found in response")
  40. ip_html = matches.group(0)
  41. return pattern_ip.search(ip_html).group(0)
  42. if __name__ == "__main__":
  43. print(get_external_ip())