diff options
author | pmoody@google.com <pmoody@google.com@09200d28-7f98-11dd-ad27-0f66e57d2035> | 2011-01-07 17:23:38 +0000 |
---|---|---|
committer | pmoody@google.com <pmoody@google.com@09200d28-7f98-11dd-ad27-0f66e57d2035> | 2011-01-07 17:23:38 +0000 |
commit | eb1dbcedad214367cc402cdca14e97074ed3ff1b (patch) | |
tree | e101c9b381b9ba13b971b146dfa194e93e3522bd /trunk/ipaddr.py | |
parent | 0a33f3f1e24a82ff26104243bf478a9729fec99b (diff) | |
download | ipaddr-py-eb1dbcedad214367cc402cdca14e97074ed3ff1b.tar.gz |
fix for i73
+ Make conversion from int to packed a public function.
this allows a user to easily construct network objects from
integers. Eg:
>>> addr # int(ipaddr.IPAddress('1.1.1.1'))
16843009
>>> ipaddr.IPNetwork('%s/24' % socket.inet_ntoa(
ipaddr.v4_int_to_packed(addr)))
IPv4Network('1.1.1.1/24')
Or
>>> addr # int(ipaddr.IPAddress('2001::1')
42540488161975842760550356425300246529L
>>> ipaddr.IPNetwork('%s/96' % socket.inet_ntop(
socket.AF_INET6, ipaddr.v6_int_to_packed(addr)))
IPv6Network('2001::1/96')
git-svn-id: https://ipaddr-py.googlecode.com/svn@198 09200d28-7f98-11dd-ad27-0f66e57d2035
Diffstat (limited to 'trunk/ipaddr.py')
-rw-r--r-- | trunk/ipaddr.py | 35 |
1 files changed, 32 insertions, 3 deletions
diff --git a/trunk/ipaddr.py b/trunk/ipaddr.py index f1706b6..e0c847a 100644 --- a/trunk/ipaddr.py +++ b/trunk/ipaddr.py @@ -29,7 +29,6 @@ import struct IPV4LENGTH = 32 IPV6LENGTH = 128 - class AddressValueError(ValueError): """A Value Error related to the address.""" @@ -119,6 +118,36 @@ def IPNetwork(address, version=None, strict=False): address) +def v4_int_to_packed(address): + """The binary representation of this address. + + Args: + address: An integer representation of an IPv4 IP address. + + Returns: + The binary representation of this address. + + Raises: + ValueError: If the integer is too large to be an IPv4 IP + address. + """ + if address > _BaseV4._ALL_ONES: + raise ValueError('Address too large for IPv4') + return struct.pack('!I', address) + + +def v6_int_to_packed(address): + """The binary representation of this address. + + Args: + address: An integer representation of an IPv4 IP address. + + Returns: + The binary representation of this address. + """ + return struct.pack('!QQ', address >> 64, address & (2**64 - 1)) + + def _find_address_range(addresses): """Find a sequence of addresses. @@ -1065,7 +1094,7 @@ class _BaseV4(object): @property def packed(self): """The binary representation of this address.""" - return struct.pack('!I', self._ip) + return v4_int_to_packed(self._ip) @property def version(self): @@ -1604,7 +1633,7 @@ class _BaseV6(object): @property def packed(self): """The binary representation of this address.""" - return struct.pack('!QQ', self._ip >> 64, self._ip & (2**64 - 1)) + return v6_int_to_packed(self._ip) @property def version(self): |