codekingpro/portable-devtools
114k
1# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license2 3# Copyright (C) 2003-2017 Nominum, Inc.4#5# Permission to use, copy, modify, and distribute this software and its6# documentation for any purpose with or without fee is hereby granted,7# provided that the above copyright notice and this permission notice8# appear in all copies.9#10# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES11# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF12# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR13# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES14# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN15# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT16# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.17 18"""IPv4 helper functions."""19 20import struct21from typing import Union22 23import dns.exception24 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.SyntaxError36 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 = text51 parts = btext.split(b".")52 if len(parts) != 4:53 raise dns.exception.SyntaxError54 for part in parts:55 if not part.isdigit():56 raise dns.exception.SyntaxError57 if len(part) > 1 and part[0] == ord("0"):58 # No leading zeros59 raise dns.exception.SyntaxError60 try:61 b = [int(part) for part in parts]62 return struct.pack("BBBB", *b)63 except Exception:64 raise dns.exception.SyntaxError65 66 67def canonicalize(text: Union[str, bytes]) -> str:68 """Verify that *address* is a valid text form IPv4 address and return its69 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 through76 # inet_ntoa() to ensure the output is a str.77 return dns.ipv4.inet_ntoa(dns.ipv4.inet_aton(text))78 