summaryrefslogtreecommitdiff
path: root/oslo_utils/netutils.py
diff options
context:
space:
mode:
authorHervé Beraud <hberaud@redhat.com>2021-02-03 10:50:50 +0100
committerHervé Beraud <hberaud@redhat.com>2021-02-05 14:07:20 +0100
commit3288539a0b3be6b69efd2630b79133b918bb079b (patch)
treec0840c39a8f53e49ac1482b58245ae8ddcac60a7 /oslo_utils/netutils.py
parent870ab370c5efff828ed04f6f1bd994a8b01b40d3 (diff)
downloadoslo-utils-3288539a0b3be6b69efd2630b79133b918bb079b.tar.gz
Add a ``strict`` flag allowing users to restrict validation of IPv4 format4.8.0
Add a ``strict`` flag allowing users to restrict validation to IP addresses in presentation format (``a.b.c.d``) as opposed to address format (``a.b.c.d``, ``a.b.c``, ``a.b``, ``a``). https://github.com/netaddr/netaddr/issues/186 https://man7.org/linux/man-pages/man3/inet_pton.3.html https://bugzilla.redhat.com/show_bug.cgi?id=1924436 Change-Id: I10fed16dad77ac17691a5d175c42b25916dc8bc4 Closes-Bug: #1914386
Diffstat (limited to 'oslo_utils/netutils.py')
-rw-r--r--oslo_utils/netutils.py31
1 files changed, 29 insertions, 2 deletions
diff --git a/oslo_utils/netutils.py b/oslo_utils/netutils.py
index 492c726..8912f17 100644
--- a/oslo_utils/netutils.py
+++ b/oslo_utils/netutils.py
@@ -24,6 +24,7 @@ import socket
from urllib import parse
import netaddr
+from netaddr.core import INET_PTON
import netifaces
from oslo_utils._i18n import _
@@ -81,17 +82,43 @@ def parse_host_port(address, default_port=None):
return (host, None if port is None else int(port))
-def is_valid_ipv4(address):
+def is_valid_ipv4(address, strict=None):
"""Verify that address represents a valid IPv4 address.
:param address: Value to verify
:type address: string
+ :param strict: flag allowing users to restrict validation
+ to IP addresses in presentation format (``a.b.c.d``) as opposed to
+ address format (``a.b.c.d``, ``a.b.c``, ``a.b``, ``a``).
+ :type flags: bool
:returns: bool
.. versionadded:: 1.1
+ .. versionchanged:: 4.8.0
+ Allow to restrict validation to IP addresses in presentation format
+ (``a.b.c.d``) as opposed to address format
+ (``a.b.c.d``, ``a.b.c``, ``a.b``, ``a``).
"""
+ if strict is not None:
+ flag = INET_PTON if strict else 0
+ try:
+ return netaddr.valid_ipv4(address, flags=flag)
+ except netaddr.AddrFormatError:
+ return False
+
+ # non strict mode
try:
- return netaddr.valid_ipv4(address)
+ if netaddr.valid_ipv4(address, flags=INET_PTON):
+ return True
+ else:
+ if netaddr.valid_ipv4(address):
+ LOG.warn(
+ 'Converting in non strict mode is deprecated. '
+ 'You should pass strict=False if you want to '
+ 'preserve legacy behavior')
+ return True
+ else:
+ return False
except netaddr.AddrFormatError:
return False