Skip to content

Commit f8b4421

Browse files
[3.11] gh-134062: Fix hash collisions in IPv4Network and IPv6Network (GH-134063) (GH-134479)
(cherry picked from commit f3fc0c1) Co-authored-by: Mike Salvatore <[email protected]>
1 parent 73b3040 commit f8b4421

File tree

3 files changed

+32
-1
lines changed

3 files changed

+32
-1
lines changed

Lib/ipaddress.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -734,7 +734,7 @@ def __eq__(self, other):
734734
return NotImplemented
735735

736736
def __hash__(self):
737-
return hash(int(self.network_address) ^ int(self.netmask))
737+
return hash((int(self.network_address), int(self.netmask)))
738738

739739
def __contains__(self, other):
740740
# always false if one is v4 and the other is v6.

Lib/test/test_ipaddress.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2685,6 +2685,34 @@ def testV6HashIsNotConstant(self):
26852685
ipv6_address2 = ipaddress.IPv6Interface("2001:658:22a:cafe:200:0:0:2")
26862686
self.assertNotEqual(ipv6_address1.__hash__(), ipv6_address2.__hash__())
26872687

2688+
# issue 134062 Hash collisions in IPv4Network and IPv6Network
2689+
def testNetworkV4HashCollisions(self):
2690+
self.assertNotEqual(
2691+
ipaddress.IPv4Network("192.168.1.255/32").__hash__(),
2692+
ipaddress.IPv4Network("192.168.1.0/24").__hash__()
2693+
)
2694+
self.assertNotEqual(
2695+
ipaddress.IPv4Network("172.24.255.0/24").__hash__(),
2696+
ipaddress.IPv4Network("172.24.0.0/16").__hash__()
2697+
)
2698+
self.assertNotEqual(
2699+
ipaddress.IPv4Network("192.168.1.87/32").__hash__(),
2700+
ipaddress.IPv4Network("192.168.1.86/31").__hash__()
2701+
)
2702+
2703+
# issue 134062 Hash collisions in IPv4Network and IPv6Network
2704+
def testNetworkV6HashCollisions(self):
2705+
self.assertNotEqual(
2706+
ipaddress.IPv6Network("fe80::/64").__hash__(),
2707+
ipaddress.IPv6Network("fe80::ffff:ffff:ffff:0/112").__hash__()
2708+
)
2709+
self.assertNotEqual(
2710+
ipaddress.IPv4Network("10.0.0.0/8").__hash__(),
2711+
ipaddress.IPv6Network(
2712+
"ffff:ffff:ffff:ffff:ffff:ffff:aff:0/112"
2713+
).__hash__()
2714+
)
2715+
26882716

26892717
if __name__ == '__main__':
26902718
unittest.main()
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
:mod:`ipaddress`: fix collisions in :meth:`~object.__hash__` for
2+
:class:`~ipaddress.IPv4Network` and :class:`~ipaddress.IPv6Network`
3+
objects.

0 commit comments

Comments
 (0)