ipv4.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. from typing import Union
  19. import dns.exception
  20. def inet_ntoa(address: bytes) -> str:
  21. """Convert an IPv4 address in binary form to text form.
  22. *address*, a ``bytes``, the IPv4 address in binary form.
  23. Returns a ``str``.
  24. """
  25. if len(address) != 4:
  26. raise dns.exception.SyntaxError
  27. return "%u.%u.%u.%u" % (address[0], address[1], address[2], address[3])
  28. def inet_aton(text: Union[str, bytes]) -> bytes:
  29. """Convert an IPv4 address in text form to binary form.
  30. *text*, a ``str`` or ``bytes``, the IPv4 address in textual form.
  31. Returns a ``bytes``.
  32. """
  33. if not isinstance(text, bytes):
  34. btext = text.encode()
  35. else:
  36. btext = text
  37. parts = btext.split(b".")
  38. if len(parts) != 4:
  39. raise dns.exception.SyntaxError
  40. for part in parts:
  41. if not part.isdigit():
  42. raise dns.exception.SyntaxError
  43. if len(part) > 1 and part[0] == ord("0"):
  44. # No leading zeros
  45. raise dns.exception.SyntaxError
  46. try:
  47. b = [int(part) for part in parts]
  48. return struct.pack("BBBB", *b)
  49. except Exception:
  50. raise dns.exception.SyntaxError
  51. def canonicalize(text: Union[str, bytes]) -> str:
  52. """Verify that *address* is a valid text form IPv4 address and return its
  53. canonical text form.
  54. *text*, a ``str`` or ``bytes``, the IPv4 address in textual form.
  55. Raises ``dns.exception.SyntaxError`` if the text is not valid.
  56. """
  57. # Note that inet_aton() only accepts canonial form, but we still run through
  58. # inet_ntoa() to ensure the output is a str.
  59. return dns.ipv4.inet_ntoa(dns.ipv4.inet_aton(text))