Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/dns/ipv4.py: 26%

27 statements  

« prev     ^ index     » next       coverage.py v7.4.1, created at 2024-02-02 06:07 +0000

1# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license 

2 

3# Copyright (C) 2003-2017 Nominum, Inc. 

4# 

5# Permission to use, copy, modify, and distribute this software and its 

6# documentation for any purpose with or without fee is hereby granted, 

7# provided that the above copyright notice and this permission notice 

8# appear in all copies. 

9# 

10# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES 

11# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 

12# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR 

13# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 

14# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 

15# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT 

16# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 

17 

18"""IPv4 helper functions.""" 

19 

20import struct 

21from typing import Union 

22 

23import dns.exception 

24 

25 

26def inet_ntoa(address: bytes) -> str: 

27 """Convert an IPv4 address in binary form to text form. 

28 

29 *address*, a ``bytes``, the IPv4 address in binary form. 

30 

31 Returns a ``str``. 

32 """ 

33 

34 if len(address) != 4: 

35 raise dns.exception.SyntaxError 

36 return "%u.%u.%u.%u" % (address[0], address[1], address[2], address[3]) 

37 

38 

39def inet_aton(text: Union[str, bytes]) -> bytes: 

40 """Convert an IPv4 address in text form to binary form. 

41 

42 *text*, a ``str`` or ``bytes``, the IPv4 address in textual form. 

43 

44 Returns a ``bytes``. 

45 """ 

46 

47 if not isinstance(text, bytes): 

48 btext = text.encode() 

49 else: 

50 btext = text 

51 parts = btext.split(b".") 

52 if len(parts) != 4: 

53 raise dns.exception.SyntaxError 

54 for part in parts: 

55 if not part.isdigit(): 

56 raise dns.exception.SyntaxError 

57 if len(part) > 1 and part[0] == ord("0"): 

58 # No leading zeros 

59 raise dns.exception.SyntaxError 

60 try: 

61 b = [int(part) for part in parts] 

62 return struct.pack("BBBB", *b) 

63 except Exception: 

64 raise dns.exception.SyntaxError 

65 

66 

67def canonicalize(text: Union[str, bytes]) -> str: 

68 """Verify that *address* is a valid text form IPv4 address and return its 

69 canonical text form. 

70 

71 *text*, a ``str`` or ``bytes``, the IPv4 address in textual form. 

72 

73 Raises ``dns.exception.SyntaxError`` if the text is not valid. 

74 """ 

75 # Note that inet_aton() only accepts canonial form, but we still run through 

76 # inet_ntoa() to ensure the output is a str. 

77 return dns.ipv4.inet_ntoa(dns.ipv4.inet_aton(text))