You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

63 lines
2.0 KiB

4 years ago
  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. from ._compat import binary_type
  20. def inet_ntoa(address):
  21. """Convert an IPv4 address in binary form to text form.
  22. *address*, a ``binary``, the IPv4 address in binary form.
  23. Returns a ``text``.
  24. """
  25. if len(address) != 4:
  26. raise dns.exception.SyntaxError
  27. if not isinstance(address, bytearray):
  28. address = bytearray(address)
  29. return ('%u.%u.%u.%u' % (address[0], address[1],
  30. address[2], address[3]))
  31. def inet_aton(text):
  32. """Convert an IPv4 address in text form to binary form.
  33. *text*, a ``text``, the IPv4 address in textual form.
  34. Returns a ``binary``.
  35. """
  36. if not isinstance(text, binary_type):
  37. text = text.encode()
  38. parts = text.split(b'.')
  39. if len(parts) != 4:
  40. raise dns.exception.SyntaxError
  41. for part in parts:
  42. if not part.isdigit():
  43. raise dns.exception.SyntaxError
  44. if len(part) > 1 and part[0] == '0':
  45. # No leading zeros
  46. raise dns.exception.SyntaxError
  47. try:
  48. bytes = [int(part) for part in parts]
  49. return struct.pack('BBBB', *bytes)
  50. except:
  51. raise dns.exception.SyntaxError