ipv4.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. # Copyright (C) 2003-2007, 2009-2011 Nominum, Inc.
  2. #
  3. # Permission to use, copy, modify, and distribute this software and its
  4. # documentation for any purpose with or without fee is hereby granted,
  5. # provided that the above copyright notice and this permission notice
  6. # appear in all copies.
  7. #
  8. # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
  9. # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  10. # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
  11. # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  12. # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  13. # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  14. # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. """IPv4 helper functions."""
  16. import struct
  17. import dns.exception
  18. from ._compat import binary_type
  19. def inet_ntoa(address):
  20. """Convert an IPv4 address in network form to text form.
  21. @param address: The IPv4 address
  22. @type address: string
  23. @returns: string
  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.%u' % (address[0], address[1],
  30. address[2], address[3])).encode()
  31. def inet_aton(text):
  32. """Convert an IPv4 address in text form to network form.
  33. @param text: The IPv4 address
  34. @type text: string
  35. @returns: string
  36. """
  37. if not isinstance(text, binary_type):
  38. text = text.encode()
  39. parts = text.split(b'.')
  40. if len(parts) != 4:
  41. raise dns.exception.SyntaxError
  42. for part in parts:
  43. if not part.isdigit():
  44. raise dns.exception.SyntaxError
  45. if len(part) > 1 and part[0] == '0':
  46. # No leading zeros
  47. raise dns.exception.SyntaxError
  48. try:
  49. bytes = [int(part) for part in parts]
  50. return struct.pack('BBBB', *bytes)
  51. except:
  52. raise dns.exception.SyntaxError