ipv4.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. # Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
  2. # Copyright (C) 2003-2017 Nominum, Inc.
  3. #
  4. # Permission to use, copy, modify, and distribute this software and its
  5. # documentation for any purpose with or without fee is hereby granted,
  6. # provided that the above copyright notice and this permission notice
  7. # appear in all copies.
  8. #
  9. # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
  10. # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  11. # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
  12. # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  13. # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  14. # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  15. # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  16. """IPv4 helper functions."""
  17. import struct
  18. import dns.exception
  19. def inet_ntoa(address: bytes) -> str:
  20. """Convert an IPv4 address in binary form to text form.
  21. *address*, a ``bytes``, the IPv4 address in binary form.
  22. Returns a ``str``.
  23. """
  24. if len(address) != 4:
  25. raise dns.exception.SyntaxError
  26. return f"{address[0]}.{address[1]}.{address[2]}.{address[3]}"
  27. def inet_aton(text: str | bytes) -> bytes:
  28. """Convert an IPv4 address in text form to binary form.
  29. *text*, a ``str`` or ``bytes``, the IPv4 address in textual form.
  30. Returns a ``bytes``.
  31. """
  32. if not isinstance(text, bytes):
  33. btext = text.encode()
  34. else:
  35. btext = text
  36. parts = btext.split(b".")
  37. if len(parts) != 4:
  38. raise dns.exception.SyntaxError
  39. for part in parts:
  40. if not part.isdigit():
  41. raise dns.exception.SyntaxError
  42. if len(part) > 1 and part[0] == ord("0"):
  43. # No leading zeros
  44. raise dns.exception.SyntaxError
  45. try:
  46. b = [int(part) for part in parts]
  47. return struct.pack("BBBB", *b)
  48. except Exception:
  49. raise dns.exception.SyntaxError
  50. def canonicalize(text: str | bytes) -> str:
  51. """Verify that *address* is a valid text form IPv4 address and return its
  52. canonical text form.
  53. *text*, a ``str`` or ``bytes``, the IPv4 address in textual form.
  54. Raises ``dns.exception.SyntaxError`` if the text is not valid.
  55. """
  56. # Note that inet_aton() only accepts canonial form, but we still run through
  57. # inet_ntoa() to ensure the output is a str.
  58. return inet_ntoa(inet_aton(text))