ipv6 cidr prefix to net mask

    :param prefix: cidr prefix, rang in (0, 128)
    :type prefix: int
    :return: comma separated ipv6 net mask code,
             eg: ffff:ffff:ffff:ffff:0000:0000:0000:0000
    :rtype: str
359377
def ipv6_prefix_to_mask(prefix):
    
    if prefix > 128 or prefix < 0:
        raise ValueError("invalid cidr prefix for ipv6")
    else:
        mask = ((1 << 128) - 1) ^ ((1 << (128 - prefix)) - 1)
        f = 15  # 0xf or 0b1111
        hex_mask_str = ''
        for i in range(0, 32):
            hex_mask_str = format((mask & f), 'x') + hex_mask_str
            mask = mask >> 4
            if i != 31 and i & 3 == 3:
                hex_mask_str = ':' + hex_mask_str
        return hex_mask_str
464947
private function addCidr( $cidr ) {
		// v4 or v6 check
		if ( strpos( $cidr, ':' ) === false ) {
			$node =& $this->root4;
			$defMask = '32';
		} else {
			$node =& $this->root6;
			$defMask = '128';
		}

		// Default to all-1's mask if no netmask in the input
		if ( strpos( $cidr, '/' ) === false ) {
			$net = $cidr;
			$mask = $defMask;
		} else {
			list( $net, $mask ) = explode( '/', $cidr, 2 );
			if ( !ctype_digit( $mask ) || intval( $mask ) > $defMask ) {
				trigger_error( "IPSet: Bad mask '$mask' from '$cidr', ignored", E_USER_WARNING );
				return false;
			}
		}
		$mask = intval( $mask ); // explicit integer convert, checked above

		// convert $net to an array of integer bytes, length 4 or 16:
		$raw = AtEase::quietCall( 'inet_pton', $net );
		if ( $raw === false ) {
			return false;
		}
		$rawOrd = array_map( 'ord', str_split( $raw ) );

		// iterate the bits of the address while walking the tree structure for inserts
		// at the end, $snode will point to the highest node that could only lead to a
		// successful match (and thus can be set to true)
		$snode =& $node;
		$curBit = 0;
		while ( 1 ) {
			if ( $node === true ) {
				// already added a larger supernet, no need to go deeper
				return;
			} elseif ( $curBit == $mask ) {
				// this may wipe out deeper subnets from earlier
				$snode = true;
				return;
			} elseif ( $node === false ) {
				// create new subarray to go deeper
				if ( !( $curBit & 7 ) && $curBit <= $mask - 8 ) {
					$node = [ 'comp' => $rawOrd[$curBit >> 3], 'next' => false ];
				} else {
					$node = [ false, false ];
				}
			}

			if ( isset( $node['comp'] ) ) {
				$comp = $node['comp'];
				if ( $rawOrd[$curBit >> 3] == $comp && $curBit <= $mask - 8 ) {
					// whole byte matches, skip over the compressed node
					$node =& $node['next'];
					$snode =& $node;
					$curBit += 8;
					continue;
				} else {
					// have to decompress the node and check individual bits
					$unode = $node['next'];
					for ( $i = 0; $i < 8; ++$i ) {
						$unode = ( $comp & ( 1 << $i ) )
							? [ false, $unode ]
							: [ $unode, false ];
					}
					$node = $unode;
				}
			}

			$maskShift = 7 - ( $curBit & 7 );
			$index = ( $rawOrd[$curBit >> 3] & ( 1 << $maskShift ) ) >> $maskShift;
			if ( $node[$index ^ 1] !== true ) {
				// no adjacent subnet, can't form a supernet at this level
				$snode =& $node[$index];
			}
			$node =& $node[$index];
			++$curBit;
		} // Unreachable outside 'while'
	}
198704
def view_prefix(arg, opts, shell_opts):
    
    # Internally, this function searches in the prefix column which means that
    # hosts have a prefix length of 32/128 while they are normally displayed
    # with the prefix length of the network they are in. To allow the user to
    # input either, e.g. 1.0.0.1 or 1.0.0.1/31 we strip the prefix length bits
    # to assume /32 if the address is not a network address. If it is the
    # network address we always search using the specified mask. In certain
    # cases there is a host with the network address, typically when /31 or /127
    # prefix lengths are used, for example 1.0.0.0/31 and 1.0.0.0/32 (first host
    # in /31 network) in which case it becomes necessary to distinguish between
    # the two using the mask.
    try:
        # this fails if bits are set on right side of mask
        ip = IPy.IP(arg)
    except ValueError:
        arg = arg.split('/')[0]

    q = { 'prefix': arg }

    v = get_vrf(opts.get('vrf_rt'), abort=True)
    if v.rt != 'all':
        q['vrf_rt'] = v.rt

    res = Prefix.list(q)

    if len(res) == 0:
        vrf_text = 'any VRF'
        if v.rt != 'all':
            vrf_text = vrf_format(v)
        print("Address %s not found in %s." % (arg, vrf_text), file=sys.stderr)
        sys.exit(1)

    p = res[0]
    vrf = p.vrf.rt

    print("-- Address ")
    print("  %-26s : %s" % ("Prefix", p.prefix))
    print("  %-26s : %s" % ("Display prefix", p.display_prefix))
    print("  %-26s : %s" % ("Type", p.type))
    print("  %-26s : %s" % ("Status", p.status))
    print("  %-26s : IPv%s" % ("Family", p.family))
    print("  %-26s : %s" % ("VRF", vrf))
    print("  %-26s : %s" % ("Description", p.description))
    print("  %-26s : %s" % ("Node", p.node))
    print("  %-26s : %s" % ("Country", p.country))
    print("  %-26s : %s" % ("Order", p.order_id))
    print("  %-26s : %s" % ("Customer", p.customer_id))
    print("  %-26s : %s" % ("VLAN", p.vlan))
    print("  %-26s : %s" % ("Alarm priority", p.alarm_priority))
    print("  %-26s : %s" % ("Monitor", p.monitor))
    print("  %-26s : %s" % ("Added", p.added))
    print("  %-26s : %s" % ("Last modified", p.last_modified))
    print("  %-26s : %s" % ("Expires", p.expires or '-'))
    if p.family == 4:
        print("  %-26s : %s / %s (%.2f%% of %s)" % ("Addresses Used / Free", p.used_addresses,
                p.free_addresses, (float(p.used_addresses)/p.total_addresses)*100,
                p.total_addresses))
    else:
        print("  %-26s : %.4e / %.4e (%.2f%% of %.4e)" % ("Addresses Used / Free", p.used_addresses,
                p.free_addresses, (float(p.used_addresses)/p.total_addresses)*100,
                p.total_addresses))
    print("-- Extra Attributes")
    if p.avps is not None:
        for key in sorted(p.avps, key=lambda s: s.lower()):
            print("  %-26s : %s" % (key, p.avps[key]))
    print("-- Tags")
    for tag_name in sorted(p.tags, key=lambda s: s.lower()):
        print("  %s" % tag_name)
    print("-- Inherited Tags")
    for tag_name in sorted(p.inherited_tags, key=lambda s: s.lower()):
        print("  %s" % tag_name)
    print("-- Comment")
    print(p.comment or '')
742726
def _inet6_ntop(addr):
    
    # IPv6 addresses have 128bits (16 bytes)
    if len(addr) != 16:
        raise ValueError("invalid length of packed IP address string")

    # Decode to hex representation
    address = ":".join(plain_str(bytes_hex(addr[idx:idx + 2])).lstrip('0') or '0'  # noqa: E501
                       for idx in range(0, 16, 2))

    try:
        # Get the longest set of zero blocks. We need to take a look
        # at group 1 regarding the length, as 0:0:1:0:0:2:3:4 would
        # have two matches: 0:0: and :0:0: where the latter is longer,
        # though the first one should be taken. Group 1 is in both
        # cases 0:0.
        match = max(_IP6_ZEROS.finditer(address),
                    key=lambda m: m.end(1) - m.start(1))
        return '{}::{}'.format(address[:match.start()], address[match.end():])
    except ValueError:
        return address
472865
def _is_valid_netmask(self, prefixlen):
        
        try:
            prefixlen = int(prefixlen)
        except ValueError:
            return False
        return 0 <= prefixlen <= self._max_prefixlen
956789
def prefixlen_to_mask(prefixlen):
    
    prefixlen = prefixlen or '32'
    addr = '0.0.0.0/%s' % prefixlen
    return str(netaddr.IPNetwork(addr).netmask)
1045384
def nth_next_sib(nth)
			if (nth < 0)
				return nil
			end
			
			shift = 32 - self.netmask.prefix_len
			addr = ((self.network.addr>>shift) + nth) << shift
			if addr > NetAddr::F32
				return nil
			end
			return IPv4Net.new(IPv4.new(addr), self.netmask)
		end
204580
def parse_ip6(ip_output, scope)
      cidr_ip = parse_ip_output(ip_output, /inet6 .* scope #{scope}/, 1)
      return unless cidr_ip

      parts = cidr_ip.split('/')
      @network_conf["address6_#{scope}".to_sym] = parts[0]
      @network_conf["prefix6_#{scope}".to_sym] = parts[1].to_i
    end
340995
def __ipv6_netmask(value):
    ''''''
    valid, errmsg = False, 'IPv6 netmask (0->128)'
    valid, value, _ = __int(value)
    valid = (valid and 0 <= value <= 128)
    return (valid, value, errmsg)
1219911
def is_valid_cidr(string_network):
    
    if string_network.count('/') == 1:
        try:
            mask = int(string_network.split('/')[1])
        except ValueError:
            return False

        if mask < 1 or mask > 32:
            return False

        try:
            socket.inet_aton(string_network.split('/')[0])
        except socket.error:
            return False
    else:
        return False
    return True
1370434
def __convertIp6PrefixStringToIp6Address(self, strIp6Prefix):
        
        prefix1 = strIp6Prefix.rstrip('L')
        prefix2 = prefix1.lstrip("0x")
        hexPrefix = str(prefix2).ljust(16,'0')
        hexIter = iter(hexPrefix)
        finalMac = ':'.join(a + b + c + d for a,b,c,d in zip(hexIter, hexIter,hexIter,hexIter))
        prefix = str(finalMac)
        strIp6Prefix = prefix[:20]
        return strIp6Prefix +':'
930516
def _ip_int_from_prefix(self, prefixlen=None):
        
        if prefixlen is None:
            prefixlen = self._prefixlen
        return self._ALL_ONES ^ (self._ALL_ONES >> prefixlen)
993353
def cidr_to_ipv4_netmask(cidr_bits):
    '''
    
    '''
    try:
        cidr_bits = int(cidr_bits)
        if not 1 <= cidr_bits <= 32:
            return ''
    except ValueError:
        return ''

    netmask = ''
    for idx in range(4):
        if idx:
            netmask += '.'
        if cidr_bits >= 8:
            netmask += '255'
            cidr_bits -= 8
        else:
            netmask += '{0:d}'.format(256 - (2 ** (8 - cidr_bits)))
            cidr_bits = 0
    return netmask
399331
def resize(prefix_len)
			m32 = Mask32.new(prefix_len)
			return IPv4Net.new(self.network,m32)
		end
297418
def str_to_ipmask(ipmask):
    '''
    
    '''
    v = ipmask.split("/")
    if len(v) > 2: raise Exception("bad mask format")
    mask_ip = ip2hex(v[0])
    if mask_ip is None: raise Exception("bad mask format")
    mask = v[1] if len(v) == 2 else 32
    try:
        mask = (0xffffffff00000000 >> int(mask)) & 0xffffffff
    except:
        mask = ip2hex(v[1])
    
    if mask is None: raise Exception("bad mask format")
    return mask_ip, mask
1216248
def in6_get6to4Prefix(addr):
    
    try:
        addr = inet_pton(socket.AF_INET, addr)
        addr = inet_ntop(socket.AF_INET6, b'\x20\x02'+addr+b'\x00'*10)
    except:
        return None
    return addr
140915
def address_in_network(ip, net):
    
    ipaddr = struct.unpack('=L', socket.inet_aton(ip))[0]
    netaddr, bits = net.split('/')
    netmask = struct.unpack('=L', socket.inet_aton(dotted_netmask(int(bits))))[0]
    network = struct.unpack('=L', socket.inet_aton(netaddr))[0] & netmask
    return (ipaddr & netmask) == (network & netmask)