ipv4.py 1.9 KB

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