Skip to content

Commit 9be4a05

Browse files
gh-161384: Fix IPv6Network.exploded with scope ID and avoid string round-trip
1 parent 5dbe2ac commit 9be4a05

3 files changed

Lines changed: 21 additions & 14 deletions

File tree

‎Lib/ipaddress.py‎

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1954,21 +1954,22 @@ def _explode_shorthand_ip_string(self):
19541954
19551955
"""
19561956
if isinstance(self, IPv6Network):
1957-
ip_str = str(self.network_address)
1958-
elif isinstance(self, IPv6Interface):
1959-
ip_str = str(self.ip)
1957+
ip_int = self.network_address._ip
1958+
scope_id = self.network_address._scope_id
19601959
else:
1961-
ip_str = self._string_from_ip_int(self._ip)
1962-
1963-
ip_int = self._ip_int_from_string(ip_str)
1964-
hex_str = '%032x' % ip_int
1965-
exploded = ':'.join([hex_str[x:x+4] for x in range(0, 32, 4)])
1966-
if isinstance(self, _BaseNetwork):
1967-
return '%s/%d' % (exploded, self._prefixlen)
1968-
if self._scope_id:
1969-
exploded = '%s%%%s' % (exploded, self._scope_id)
1970-
if isinstance(self, IPv6Interface):
1971-
return '%s/%d' % (exploded, self._prefixlen)
1960+
ip_int = self._ip
1961+
scope_id = self._scope_id
1962+
1963+
exploded = (
1964+
f'{ip_int >> 112:04x}:{(ip_int >> 96) & 0xFFFF:04x}:'
1965+
f'{(ip_int >> 80) & 0xFFFF:04x}:{(ip_int >> 64) & 0xFFFF:04x}:'
1966+
f'{(ip_int >> 48) & 0xFFFF:04x}:{(ip_int >> 32) & 0xFFFF:04x}:'
1967+
f'{(ip_int >> 16) & 0xFFFF:04x}:{ip_int & 0xFFFF:04x}'
1968+
)
1969+
if scope_id:
1970+
exploded = f'{exploded}%{scope_id}'
1971+
if isinstance(self, (_BaseNetwork, IPv6Interface)):
1972+
return f'{exploded}/{self._prefixlen}'
19721973
return exploded
19731974

19741975
def _reverse_pointer(self):

‎Lib/test/test_ipaddress.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2807,6 +2807,10 @@ def testExplodeShortHandIpStr(self):
28072807
ipaddress.IPv6Address('fe80::1%eth0').exploded)
28082808
self.assertEqual('fe80:0000:0000:0000:0000:0000:0000:0001%1/64',
28092809
ipaddress.IPv6Interface('fe80::1%1/64').exploded)
2810+
self.assertEqual('fe80:0000:0000:0000:0000:0000:0000:0000%eth0/64',
2811+
ipaddress.IPv6Network('fe80::%eth0/64').exploded)
2812+
self.assertEqual('fe80:0000:0000:0000:0000:0000:0000:0000%1/64',
2813+
ipaddress.IPv6Network('fe80::%1/64').exploded)
28102814
# issue 77
28112815
self.assertEqual('2001:0000:5ef5:79fd:0000:059d:a0e5:0ba1',
28122816
addr2.exploded)
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix :attr:`ipaddress.IPv6Network.exploded` for networks with a scope ID and
2+
avoid redundant string round-tripping in ``_BaseV6._explode_shorthand_ip_string()``.

0 commit comments

Comments
 (0)