| 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 |
|
| 20 |
import struct |
| 21 |
|
| 22 |
import dns.exception |
| 23 |
|
| 24 |
|
| 25 |
def inet_ntoa(address: bytes) -> str: |
| 26 |
"""Convert an IPv4 address in binary form to text form. |
| 27 |
|
| 28 |
*address*, a ``bytes``, the IPv4 address in binary form. |
| 29 |
|
| 30 |
Returns a ``str``. |
| 31 |
""" |
| 32 |
|
| 33 |
if len(address) != 4: |
| 34 |
raise dns.exception.SyntaxError |
| 35 |
return f"{address[0]}.{address[1]}.{address[2]}.{address[3]}" |
| 36 |
|
| 37 |
|
| 38 |
def inet_aton(text: str | bytes) -> bytes: |
| 39 |
"""Convert an IPv4 address in text form to binary form. |
| 40 |
|
| 41 |
*text*, a ``str`` or ``bytes``, the IPv4 address in textual form. |
| 42 |
|
| 43 |
Returns a ``bytes``. |
| 44 |
""" |
| 45 |
|
| 46 |
if not isinstance(text, bytes): |
| 47 |
btext = text.encode() |
| 48 |
else: |
| 49 |
btext = text |
| 50 |
parts = btext.split(b".") |
| 51 |
if len(parts) != 4: |
| 52 |
raise dns.exception.SyntaxError |
| 53 |
for part in parts: |
| 54 |
if not part.isdigit(): |
| 55 |
raise dns.exception.SyntaxError |
| 56 |
if len(part) > 1 and part[0] == ord("0"): |
| 57 |
# No leading zeros |
| 58 |
raise dns.exception.SyntaxError |
| 59 |
try: |
| 60 |
b = [int(part) for part in parts] |
| 61 |
return struct.pack("BBBB", *b) |
| 62 |
except Exception: |
| 63 |
raise dns.exception.SyntaxError |
| 64 |
|
| 65 |
|
| 66 |
def canonicalize(text: str | bytes) -> str: |
| 67 |
"""Verify that *address* is a valid text form IPv4 address and return its |
| 68 |
canonical text form. |
| 69 |
|
| 70 |
*text*, a ``str`` or ``bytes``, the IPv4 address in textual form. |
| 71 |
|
| 72 |
Raises ``dns.exception.SyntaxError`` if the text is not valid. |
| 73 |
""" |
| 74 |
# Note that inet_aton() only accepts canonial form, but we still run through |
| 75 |
# inet_ntoa() to ensure the output is a str. |
| 76 |
return inet_ntoa(inet_aton(text)) |