From 117510c2f52cec190c9bf59a674791c5d6d8a734 Mon Sep 17 00:00:00 2001 From: Markus Koetter Date: Sun, 14 Jun 2015 12:38:51 +0200 Subject: [PATCH] Fix use of ipaddress for INET types with netmask using ip_interface/IPvXInterface --- postgresql/test/test_driver.py | 2 ++ postgresql/types/io/pg_network.py | 11 +++++++---- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/postgresql/test/test_driver.py b/postgresql/test/test_driver.py index 9c81bab9..b66541d2 100644 --- a/postgresql/test/test_driver.py +++ b/postgresql/test/test_driver.py @@ -294,11 +294,13 @@ ipaddress.IPv4Address('255.255.255.255'), ipaddress.IPv4Address('127.0.0.1'), ipaddress.IPv4Address('10.0.0.1'), + ipaddress.IPv4Interface('10.0.0.1/24'), ipaddress.IPv4Address('0.0.0.0'), ipaddress.IPv6Address('::1'), ipaddress.IPv6Address('ffff' + ':ffff'*7), ipaddress.IPv6Address('fe80::1'), ipaddress.IPv6Address('fe80::1'), + ipaddress.IPv6Interface('fe80::1/64'), ipaddress.IPv6Address('::'), # 0::0 ], ), diff --git a/postgresql/types/io/pg_network.py b/postgresql/types/io/pg_network.py index a74d5e16..d107d926 100644 --- a/postgresql/types/io/pg_network.py +++ b/postgresql/types/io/pg_network.py @@ -8,17 +8,20 @@ CIDROID: ipaddress._BaseNetwork, } -def inet_pack(ob, pack = lib.net_pack, Constructor = ipaddress.ip_address): +def inet_pack(ob, pack = lib.net_pack, Constructor = ipaddress.ip_interface): a = Constructor(ob) - return pack((a.version, None, a.packed)) + return pack((a.version, a.network.prefixlen, a.packed)) def cidr_pack(ob, pack = lib.net_pack, Constructor = ipaddress.ip_network): a = Constructor(ob) return pack((a.version, a.prefixlen, a.network_address.packed)) -def inet_unpack(data, unpack = lib.net_unpack, Constructor = ipaddress.ip_address): +def inet_unpack(data, unpack = lib.net_unpack, Constructor = ipaddress.ip_interface): version, mask, data = unpack(data) - return Constructor(data) + if (version == 4 and mask == 32) or (version == 6 and mask == 128): + return ipaddress.ip_address(data) + else: + return Constructor("{addr}/{mask}".format(addr=ipaddress.ip_address(data), mask=mask)) def cidr_unpack(data, unpack = lib.net_unpack, Constructor = ipaddress.ip_network): version, mask, data = unpack(data)