Skip to content

Commit

Permalink
Fix handling of CIDR input to "inet" data type
Browse files Browse the repository at this point in the history
PostgreSQL actually allows network addresses in "inet", so handle this.

Fixes: #37
  • Loading branch information
elprans committed Nov 14, 2016
1 parent 5ca0b07 commit 2707ca3
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
12 changes: 9 additions & 3 deletions asyncpg/protocol/codecs/network.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ cdef net_decode(ConnectionSettings settings, FastReadBuffer buf):

addr = cpython.PyBytes_FromStringAndSize(buf.read(addrlen), addrlen)

if is_cidr:
if is_cidr or bits > 0:
return _ipnet(addr).supernet(new_prefix=cpython.PyLong_FromLong(bits))
else:
return _ipaddr(addr)
Expand All @@ -81,8 +81,14 @@ cdef inet_encode(ConnectionSettings settings, WriteBuffer buf, obj):
cdef:
object ipaddr

ipaddr = _ipaddr(obj)
_net_encode(buf, ipaddr.version, 0, 0, ipaddr.packed)
try:
ipaddr = _ipaddr(obj)
except ValueError:
# PostgreSQL accepts *both* CIDR and host values
# for the host datatype.
cidr_encode(settings, buf, obj)
else:
_net_encode(buf, ipaddr.version, 0, 0, ipaddr.packed)


cdef init_network_codecs():
Expand Down
6 changes: 6 additions & 0 deletions tests/test_codecs.py
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,12 @@ def _timezone(offset):
ipaddress.IPv6Address('ffff' + ':ffff' * 7),
ipaddress.IPv6Address('::1'),
ipaddress.IPv6Address('::'),
dict(
input='127.0.0.0/8',
output=ipaddress.IPv4Network('127.0.0.0/8')),
dict(
input='127.0.0.1/32',
output=ipaddress.IPv4Network('127.0.0.1/32')),
]),
('macaddr', 'macaddr', [
'00:00:00:00:00:00',
Expand Down

0 comments on commit 2707ca3

Please sign in to comment.