From 8de87255bfea0b07742f5d017327f1a374c69dc1 Mon Sep 17 00:00:00 2001 From: Bob Halley Date: Mon, 4 May 2020 06:51:15 -0700 Subject: [PATCH] Add an ignore_scope option to dns.ipv6.inet_aton(). --- dns/ipv6.py | 13 ++++++++++++- tests/test_ntoaaton.py | 17 +++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/dns/ipv6.py b/dns/ipv6.py index 1f703a67..43934cd4 100644 --- a/dns/ipv6.py +++ b/dns/ipv6.py @@ -96,11 +96,14 @@ _v4_ending = re.compile(br'(.*):(\d+\.\d+\.\d+\.\d+)$') _colon_colon_start = re.compile(br'::.*') _colon_colon_end = re.compile(br'.*::$') -def inet_aton(text): +def inet_aton(text, ignore_scope=False): """Convert an IPv6 address in text form to binary form. *text*, a ``text``, the IPv6 address in textual form. + *ignore_scope*, a ``bool``. If ``True``, a scope will be ignored. + If ``False``, the default, it is an error for a scope to be present. + Returns a ``bytes``. """ @@ -110,6 +113,14 @@ def inet_aton(text): if not isinstance(text, bytes): text = text.encode() + if ignore_scope: + parts = text.split(b'%') + l = len(parts) + if l == 2: + text = parts[0] + elif l > 2: + raise dns.exception.SyntaxError + if text == b'::': text = b'0::' # diff --git a/tests/test_ntoaaton.py b/tests/test_ntoaaton.py index 2da0da6c..ba6cc30c 100644 --- a/tests/test_ntoaaton.py +++ b/tests/test_ntoaaton.py @@ -226,5 +226,22 @@ class NtoAAtoNTestCase(unittest.TestCase): self.assertFalse(dns.inet.is_multicast(t5)) self.assertTrue(dns.inet.is_multicast(t6)) + def test_ignore_scope(self): + t1 = 'fe80::1%lo0' + t2 = 'fe80::1' + self.assertEqual(aton6(t1, True), aton6(t2)) + + def test_do_not_ignore_scope(self): + def bad(): + t1 = 'fe80::1%lo0' + aton6(t1) + self.assertRaises(dns.exception.SyntaxError, bad) + + def test_multiple_scopes_bad(self): + def bad(): + t1 = 'fe80::1%lo0%lo1' + aton6(t1, True) + self.assertRaises(dns.exception.SyntaxError, bad) + if __name__ == '__main__': unittest.main() -- 2.47.3