gh-134062: Fix hash collisions in IPv4Network and IPv6Network (GH-134063)

gh-134062: Fix hash collisions in IPv4Network and IPv6Network
gh-134062: Add hash collision regression test
This commit is contained in:
Mike Salvatore 2025-05-21 22:48:10 -04:00 committed by GitHub
parent 518c95b552
commit f3fc0c16e0
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 32 additions and 1 deletions

View file

@ -729,7 +729,7 @@ class _BaseNetwork(_IPAddressBase):
return NotImplemented
def __hash__(self):
return hash(int(self.network_address) ^ int(self.netmask))
return hash((int(self.network_address), int(self.netmask)))
def __contains__(self, other):
# always false if one is v4 and the other is v6.

View file

@ -2762,6 +2762,34 @@ class IpaddrUnitTest(unittest.TestCase):
ipv6_address2 = ipaddress.IPv6Interface("2001:658:22a:cafe:200:0:0:2")
self.assertNotEqual(ipv6_address1.__hash__(), ipv6_address2.__hash__())
# issue 134062 Hash collisions in IPv4Network and IPv6Network
def testNetworkV4HashCollisions(self):
self.assertNotEqual(
ipaddress.IPv4Network("192.168.1.255/32").__hash__(),
ipaddress.IPv4Network("192.168.1.0/24").__hash__()
)
self.assertNotEqual(
ipaddress.IPv4Network("172.24.255.0/24").__hash__(),
ipaddress.IPv4Network("172.24.0.0/16").__hash__()
)
self.assertNotEqual(
ipaddress.IPv4Network("192.168.1.87/32").__hash__(),
ipaddress.IPv4Network("192.168.1.86/31").__hash__()
)
# issue 134062 Hash collisions in IPv4Network and IPv6Network
def testNetworkV6HashCollisions(self):
self.assertNotEqual(
ipaddress.IPv6Network("fe80::/64").__hash__(),
ipaddress.IPv6Network("fe80::ffff:ffff:ffff:0/112").__hash__()
)
self.assertNotEqual(
ipaddress.IPv4Network("10.0.0.0/8").__hash__(),
ipaddress.IPv6Network(
"ffff:ffff:ffff:ffff:ffff:ffff:aff:0/112"
).__hash__()
)
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,3 @@
:mod:`ipaddress`: fix collisions in :meth:`~object.__hash__` for
:class:`~ipaddress.IPv4Network` and :class:`~ipaddress.IPv6Network`
objects.