github.com/rawahars/moby@v24.0.4+incompatible/libnetwork/ipam/utils.go (about)

     1  package ipam
     2  
     3  import (
     4  	"net"
     5  	"net/netip"
     6  
     7  	"github.com/docker/docker/libnetwork/ipbits"
     8  )
     9  
    10  func toIPNet(p netip.Prefix) *net.IPNet {
    11  	if !p.IsValid() {
    12  		return nil
    13  	}
    14  	return &net.IPNet{
    15  		IP:   p.Addr().AsSlice(),
    16  		Mask: net.CIDRMask(p.Bits(), p.Addr().BitLen()),
    17  	}
    18  }
    19  
    20  func toPrefix(n *net.IPNet) (netip.Prefix, bool) {
    21  	if ll := len(n.Mask); ll != net.IPv4len && ll != net.IPv6len {
    22  		return netip.Prefix{}, false
    23  	}
    24  
    25  	addr, ok := netip.AddrFromSlice(n.IP)
    26  	if !ok {
    27  		return netip.Prefix{}, false
    28  	}
    29  
    30  	ones, bits := n.Mask.Size()
    31  	if ones == 0 && bits == 0 {
    32  		return netip.Prefix{}, false
    33  	}
    34  
    35  	return netip.PrefixFrom(addr.Unmap(), ones), true
    36  }
    37  
    38  func hostID(addr netip.Addr, bits uint) uint64 {
    39  	return ipbits.Field(addr, bits, uint(addr.BitLen()))
    40  }
    41  
    42  // subnetRange returns the amount to add to network.Addr() in order to yield the
    43  // first and last addresses in subnet, respectively.
    44  func subnetRange(network, subnet netip.Prefix) (start, end uint64) {
    45  	start = hostID(subnet.Addr(), uint(network.Bits()))
    46  	end = start + (1 << uint64(subnet.Addr().BitLen()-subnet.Bits())) - 1
    47  	return start, end
    48  }