Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/module_utils/ipaddress.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (c) 2018 F5 Networks Inc.
4 # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 from __future__ import absolute_import, division, print_function
7 __metaclass__ = type
8
9 from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import (
10 validate_ip_address, validate_ip_v6_address
11 )
12
13 from ipaddress import ip_interface, ip_network
14
15
16 def is_valid_ip(addr, type='all'):
17 if type in ['all', 'ipv4']:
18 if validate_ip_address(addr):
19 return True
20 if type in ['all', 'ipv6']:
21 if validate_ip_v6_address(addr):
22 return True
23 return False
24
25
26 def ipv6_netmask_to_cidr(mask):
27 """converts an IPv6 netmask to CIDR form
28
29 According to the link below, CIDR is the only official way to specify
30 a subset of IPv6. With that said, the same link provides a way to
31 loosely convert an netmask to a CIDR.
32
33 Arguments:
34 mask (string): The IPv6 netmask to convert to CIDR
35
36 Returns:
37 int: The CIDR representation of the netmask
38
39 References:
40 https://stackoverflow.com/a/33533007
41 http://v6decode.com/
42 """
43 bit_masks = [
44 0, 0x8000, 0xc000, 0xe000, 0xf000, 0xf800,
45 0xfc00, 0xfe00, 0xff00, 0xff80, 0xffc0,
46 0xffe0, 0xfff0, 0xfff8, 0xfffc, 0xfffe,
47 0xffff
48 ]
49 count = 0
50 try:
51 for w in mask.split(':'):
52 if not w or int(w, 16) == 0:
53 break
54 count += bit_masks.index(int(w, 16))
55 return count
56 except Exception:
57 return -1
58
59
60 def is_valid_ip_network(address):
61 try:
62 ip_network(u'{0}'.format(address))
63 return True
64 except ValueError:
65 return False
66
67
68 def is_valid_ip_interface(address):
69 try:
70 ip_interface(u'{0}'.format(address))
71 return True
72 except ValueError:
73 return False
74
75
76 def get_netmask(address):
77 addr = ip_network(u'{0}'.format(address))
78 netmask = addr.netmask.compressed
79 return netmask
80
81
82 def compress_address(address):
83 addr = ip_network(u'{0}'.format(address))
84 result = addr.compressed.split('/', maxsplit=1)[0]
85 return result