Traffic scripts: Move valid_ipv* to a library
[csit.git] / GPL / traffic_scripts / ValidIp.py
1 #!/usr/bin/env python3
2
3 # Copyright (c) 2021 Cisco and/or its affiliates.
4 #
5 # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
6 #
7 # Licensed under the Apache License 2.0 or
8 # GNU General Public License v2.0 or later;  you may not use this file
9 # except in compliance with one of these Licenses. You
10 # may obtain a copy of the Licenses at:
11 #
12 #     http://www.apache.org/licenses/LICENSE-2.0
13 #     https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html
14 #
15 # Note: If this file is linked with Scapy, which is GPLv2+, your use of it
16 # must be under GPLv2+.  If at any point in the future it is no longer linked
17 # with Scapy (or other GPLv2+ licensed software), you are free to choose
18 # Apache 2.
19 #
20 # Unless required by applicable law or agreed to in writing, software
21 # distributed under the License is distributed on an "AS IS" BASIS,
22 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
23 # See the License for the specific language governing permissions and
24 # limitations under the License.
25
26 """Functions simplifying address validation."""
27
28 import ipaddress
29
30
31 def valid_ipv4(ip_address):
32     """Check IPv4 address.
33
34     :param ip_address: IPv4 address to check.
35     :type ip_address: str
36     :returns: True if IP address is correct.
37     :rtype: bool
38     """
39     try:
40         ipaddress.IPv4Address(ip_address)
41         return True
42     except (AttributeError, ipaddress.AddressValueError):
43         return False
44
45
46 def valid_ipv6(ip_address):
47     """Check IPv6 address.
48
49     :param ip_address: IPv6 address to check.
50     :type ip_address: str
51     :returns: True if IP address is correct.
52     :rtype: bool
53     """
54     try:
55         ipaddress.IPv6Address(ip_address)
56         return True
57     except (AttributeError, ipaddress.AddressValueError):
58         return False