// FIXME this only handles IPv4 at the moment
175122
func spliceIP(baseIP, partialIP string) string {
	baseParts := strings.Split(baseIP, ".")
	partialParts := strings.Split(partialIP, ".")
	finalParts := append(baseParts[:(len(baseParts)-len(partialParts))], partialParts...)
	return strings.Join(finalParts, ".")
}
127801
func kvmSetupNetAddressing(network *Networking, n activeNet, ifName string) error {
	// TODO: very ugly hack, that go through upper plugin, down to ipam plugin
	if err := ip.EnableIP4Forward(); err != nil {
		return errwrap.Wrap(errors.New("failed to enable forwarding"), err)
	}

	// patch plugin type only for single IPAM run time, then revert this change
	original_type := n.conf.Type
	n.conf.Type = n.conf.IPAM.Type
	output, err := network.execNetPlugin("ADD", &n, ifName)
	n.conf.Type = original_type
	if err != nil {
		return errwrap.Wrap(fmt.Errorf("problem executing network plugin %q (%q)", n.conf.IPAM.Type, ifName), err)
	}

	result := cnitypes.Result{}
	if err = json.Unmarshal(output, &result); err != nil {
		return errwrap.Wrap(fmt.Errorf("error parsing %q result", n.conf.Name), err)
	}

	if result.IP4 == nil {
		return fmt.Errorf("net-plugin returned no IPv4 configuration")
	}

	n.runtime.MergeCNIResult(result)

	return nil
}
915901
func (r *CacheResolver) Resolve(host string) ([]net.IP, error) {
	r.mu.RLock()
	if item, ok := r.cache[host]; ok {
		if item.ttl.IsZero() || timeNow().Before(item.ttl) {
			r.mu.RUnlock()
			ips := make([]net.IP, len(item.ips))
			copy(ips, item.ips)
			return ips, nil
		}
	}
	r.mu.RUnlock()

	resolver := r.Resolver
	if resolver == nil {
		resolver = DefaultResolver
	}
	ips, err := resolver.Resolve(host)
	if err != nil {
		return nil, err
	}

	var ttl time.Time
	if r.TTL > 0 {
		ttl = timeNow().Add(r.TTL)
	}
	item := &cacheItem{ips, ttl}
	r.mu.Lock()
	if r.cache == nil {
		r.cache = make(map[string]*cacheItem)
	}
	r.cache[host] = item
	r.mu.Unlock()

	ips = make([]net.IP, len(item.ips))
	copy(ips, item.ips)
	return ips, err
}
265542
func MyIp6() *net.IPAddr {
	myIp6Once.Do(func() {
		var err error
		myIp6, err = net.ResolveIPAddr("ip6", MyHostname())
		if err != nil {
			log.Fatal(err)
		}
	})
	return myIp6
}
1123870
func (cache *NPHDSCache) handleIPDelete(npHost *envoyAPI.NetworkPolicyHosts, peerIdentity, peerIP string) {
	targetIndex := -1

	scopedLog := log.WithFields(logrus.Fields{
		logfields.IPAddr:       peerIP,
		logfields.Identity:     peerIdentity,
		logfields.Modification: ipcache.Delete,
	})
	for i, endpointIP := range npHost.HostAddresses {
		if endpointIP == peerIP {
			targetIndex = i
			break
		}
	}
	if targetIndex < 0 {
		scopedLog.Warning("Can't find IP in NPHDS cache")
		return
	}

	// If removing this host would result in empty list, delete it.
	// Otherwise, update to a list that doesn't contain the target IP
	if len(npHost.HostAddresses) <= 1 {
		cache.Delete(NetworkPolicyHostsTypeURL, peerIdentity, false)
	} else {
		// If the resource is to be updated, create a copy of it before
		// removing the IP address from its HostAddresses list.
		hostAddresses := make([]string, 0, len(npHost.HostAddresses)-1)
		if len(npHost.HostAddresses) == targetIndex {
			hostAddresses = append(hostAddresses, npHost.HostAddresses[0:targetIndex]...)
		} else {
			hostAddresses = append(hostAddresses, npHost.HostAddresses[0:targetIndex]...)
			hostAddresses = append(hostAddresses, npHost.HostAddresses[targetIndex+1:]...)
		}

		newNpHost := envoyAPI.NetworkPolicyHosts{
			Policy:        uint64(npHost.Policy),
			HostAddresses: hostAddresses,
		}
		if err := newNpHost.Validate(); err != nil {
			scopedLog.WithError(err).Warning("Could not validate NPHDS resource update on delete")
			return
		}
		cache.Upsert(NetworkPolicyHostsTypeURL, peerIdentity, &newNpHost, false)
	}
}
1005985
func DefaultLocalIP4() (net.IP, error) {
	devices, err := net.Interfaces()
	if err != nil {
		return nil, err
	}
	for _, dev := range devices {
		if (dev.Flags&net.FlagUp != 0) && (dev.Flags&net.FlagLoopback == 0) {
			addrs, err := dev.Addrs()
			if err != nil {
				continue
			}
			for i := range addrs {
				if ip, ok := addrs[i].(*net.IPNet); ok {
					if ip.IP.To4() != nil {
						return ip.IP, nil
					}
				}
			}
		}
	}
	return nil, ErrorNoDefaultIP
}
244409
func (h *Hostsfile) LookupStaticHostV4(host string) []net.IP {
	return h.lookupStaticHost(h.hmap.byNameV4, host)
}
1145614
func (p *Packet) FixupIPHdrOnDataModify(old, new uint16) {
	// IP Header Processing
	// IP chekcsum fixup.
	p.ipHdr.ipChecksum = incCsum16(p.ipHdr.ipChecksum, old, new)
	// Update IP Total Length.
	p.ipHdr.ipTotalLength = p.ipHdr.ipTotalLength + new - old

	binary.BigEndian.PutUint16(p.ipHdr.Buffer[ipv4LengthPos:ipv4LengthPos+2], p.ipHdr.ipTotalLength)
	binary.BigEndian.PutUint16(p.ipHdr.Buffer[ipv4ChecksumPos:ipv4ChecksumPos+2], p.ipHdr.ipChecksum)
}
291776
func (p *parserMixin) ResolvedIPList() (target *[]net.IP) {
	target = new([]net.IP)
	p.ResolvedIPListVar(target)
	return
}
735742
func (ipv4 IPv4Addr) NetIPMask() *net.IPMask {
	ipv4Mask := net.IPMask{}
	ipv4Mask = make(net.IPMask, IPv4len)
	binary.BigEndian.PutUint32(ipv4Mask, uint32(ipv4.Mask))
	return &ipv4Mask
}
1205264
func (p *parserMixin) ResolvedIP() (target *net.IP) {
	target = new(net.IP)
	p.ResolvedIPVar(target)
	return
}
458687
func WithIPv4Mask(mask net.IPMask) Option {
	return func(o *Options) {
		o.IPv4Mask = mask
	}
}
128540
func NetAddrIPPROTO(addr net.Addr) int {
	switch addr := addr.(type) {
	case *net.IPAddr:
		switch {
		default:
			return IPPROTO_IP

		case addr.IP.To4() != nil:
			return IPPROTO_IPV4

		case addr.IP.To16() != nil:
			return IPPROTO_IPV6
		}

	case *net.TCPAddr:
		return IPPROTO_TCP

	case *net.UDPAddr:
		return IPPROTO_UDP

	default:
		return -1
	}
}
1262880
func ConvertIPv4InIPv6Network(network, ip string) (*net.IPNet, error) {
	// parse original network
	_, pNet1, err := net.ParseCIDR(network)
	if err != nil {
		return nil, err
	}

	// create an empty network
	_, pNet2, err := net.ParseCIDR("0::/63")
	if err != nil {
		return nil, err
	}

	// set 2 last bytes in new network
	ip2 := net.ParseIP(ip)
	pNet2.IP[0] = ip2[14]
	pNet2.IP[1] = ip2[15]

	// we shift network to follow the first ip
	shift, _ := pNet1.Mask.Size()
	pNet2.IP = SliceShiftRight(pNet2.IP, uint(shift))

	// return the OR of joined network
	return IPNetOr(pNet1, pNet2), nil
}
1309883
func ResolveSchemeFromVHost(vhost string) string {
	// pure check
	isTLS := strings.HasPrefix(vhost, SchemeHTTPS) || ResolvePort(vhost) == 443
	return ResolveScheme(isTLS)
}
247998
func IPv4Routes(addr *models.NodeAddressing, linkMTU int) ([]route.Route, error) {
	ip := net.ParseIP(addr.IPV4.IP)
	if ip == nil {
		return []route.Route{}, fmt.Errorf("Invalid IP address: %s", addr.IPV4.IP)
	}
	return []route.Route{
		{
			Prefix: net.IPNet{
				IP:   ip,
				Mask: defaults.ContainerIPv4Mask,
			},
		},
		{
			Prefix:  defaults.IPv4DefaultRoute,
			Nexthop: &ip,
			MTU:     linkMTU,
		},
	}, nil
}
206939
func ResolveVHost(addr string) string {
	if addr == ":https" || addr == ":http" {
		return "localhost"
	}

	if idx := strings.IndexByte(addr, ':'); idx == 0 {
		// only port, then return the localhost hostname
		return "localhost" + addr[idx:]
	}

	// with ':' in order to not replace the ipv6 loopback addresses
	addr = strings.Replace(addr, "0.0.0.0:", "localhost:", 1)
	port := ResolvePort(addr)
	if port == 80 || port == 443 {
		return ResolveHostname(addr)
	}

	return addr
}