Package dns :: Module ipv4 |
[hide private]
[frames] | no frames]

# Source Code for Module dns.ipv4

     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
    16  """IPv4 helper functions."""
    17
    18  import struct
    19
    20  import dns.exception
    21  from ._compat import binary_type
    22
    23 -def inet_ntoa(address):
    24      """Convert an IPv4 address in network form to text form.
    25
    26      @param address: The IPv4 address
    27      @type address: string
    28      @returns: string
    29      """
    30      if len(address) != 4:
    31          raise dns.exception.SyntaxError
    32      if not isinstance(address, bytearray):
    33          address = bytearray(address)
    34      return (u'%u.%u.%u.%u' % (address[0], address[1],
    35                                address[2], address[3])).encode()
    36
    37 -def inet_aton(text):
    38      """Convert an IPv4 address in text form to network form.
    39
    40      @param text: The IPv4 address
    41      @type text: string
    42      @returns: string
    43      """
    44      if not isinstance(text, binary_type):
    45          text = text.encode()
    46      parts = text.split(b'.')
    47      if len(parts) != 4:
    48          raise dns.exception.SyntaxError
    49      for part in parts:
    50          if not part.isdigit():
    51              raise dns.exception.SyntaxError
    52          if len(part) > 1 and part[0] == '0':
    53              # No leading zeros
    54              raise dns.exception.SyntaxError
    55      try:
    56          bytes = [int(part) for part in parts]
    57          return struct.pack('BBBB', *bytes)
    58      except:
    59          raise dns.exception.SyntaxError
    60