// AddressBinString returns a string with the IPv6Addr's Address represented
// as a sequence of '0' and '1' characters.  This method is useful for
// debugging or by operators who want to inspect an address.
182189
func (ipv6 IPv6Addr) AddressBinString() string {
	bi := big.Int(*ipv6.Address)
	return fmt.Sprintf("%0128s", bi.Text(2))
}
68346
func (a *AddrManager) HostToNetAddress(host string, port uint16, services wire.ServiceFlag) (*wire.NetAddress, error) {
	// Tor address is 16 char base32 + ".onion"
	var ip net.IP
	if len(host) == 22 && host[16:] == ".onion" {
		// go base32 encoding uses capitals (as does the rfc
		// but Tor and bitcoind tend to user lowercase, so we switch
		// case here.
		data, err := base32.StdEncoding.DecodeString(
			strings.ToUpper(host[:16]))
		if err != nil {
			return nil, err
		}
		prefix := []byte{0xfd, 0x87, 0xd8, 0x7e, 0xeb, 0x43}
		ip = net.IP(append(prefix, data...))
	} else if ip = net.ParseIP(host); ip == nil {
		ips, err := a.lookupFunc(host)
		if err != nil {
			return nil, err
		}
		if len(ips) == 0 {
			return nil, fmt.Errorf("no addresses found for %s", host)
		}
		ip = ips[0]
	}

	return wire.NewNetAddressIPPort(ip, port, services), nil
}
1293080
func AllocAddressHandler(w http.ResponseWriter, r *http.Request, vars map[string]string) (interface{}, error) {
	var allocReq AddressAllocRequest
	var epgCfg *mastercfg.EndpointGroupState
	var networkID string
	var epgName string

	// Get object from the request
	err := json.NewDecoder(r.Body).Decode(&allocReq)
	if err != nil {
		log.Errorf("Error decoding AllocAddressHandler. Err %v", err)
		return nil, err
	}

	log.Infof("Received AddressAllocRequest: %+v", allocReq)

	// Take a global lock for address allocation
	addrMutex.Lock()
	defer addrMutex.Unlock()

	// Get hold of the state driver
	stateDriver, err := utils.GetStateDriver()
	if err != nil {
		return nil, err
	}

	isIPv6 := netutils.IsIPv6(allocReq.AddressPool)

	// Determine the network id to use
	if allocReq.NetworkID != "" {
		networkID, epgName = getNwAndEpgFromAddrReq(allocReq.NetworkID)
	} else {
		// find the network from address pool
		subnetIP := strings.Split(allocReq.AddressPool, "/")[0]
		subnetLen := strings.Split(allocReq.AddressPool, "/")[1]
		tenant := ""
		if strings.Contains(subnetLen, ":") {
			tenant = strings.Split(subnetLen, ":")[1]
			subnetLen = strings.Split(subnetLen, ":")[0]
		}

		// find the network from networkID
		readNet := &mastercfg.CfgNetworkState{}
		readNet.StateDriver = stateDriver
		netList, err := readNet.ReadAll()
		if err != nil {
			if !strings.Contains(err.Error(), "key not found") {
				log.Errorf("error reading keys during host create. Error: %s", err)
				return nil, err
			}
		}

		for _, ncfg := range netList {
			nw := ncfg.(*mastercfg.CfgNetworkState)
			if isIPv6 && nw.IPv6Subnet == subnetIP && fmt.Sprintf("%d", nw.IPv6SubnetLen) == subnetLen {
				if tenant == "" || nw.Tenant == tenant {
					networkID = nw.ID
				}
			} else if nw.SubnetIP == subnetIP && fmt.Sprintf("%d", nw.SubnetLen) == subnetLen {
				if tenant == "" || nw.Tenant == tenant {
					networkID = nw.ID
				}
			}
		}
	}

	if len(epgName) > 0 {
		epgCfg = &mastercfg.EndpointGroupState{}
		epgCfg.StateDriver = stateDriver
		if err = epgCfg.Read(epgName); err != nil {
			log.Errorf("failed to read epg %s, %s", epgName, err)
			return nil, err
		}
		log.Infof("AddressAllocRequest for network: %s epg: %s", networkID, epgName)
	}

	if networkID == "" {
		if GetClusterMode() == core.SwarmMode {
			// If the network was created using docker command,
			// we get allocReq before the network is created. Here,
			// we return the first IP in the subnet as gateway IP.
			// Subsequent createNetwork request will come with
			// a subnet and gateway which will allocate the gateway IP
			var ipAddress string
			var subnetLen uint
			subnetIP := strings.Split(allocReq.AddressPool, "/")[0]
			subnetLen = func() uint {
				p, err := strconv.Atoi(strings.Split(allocReq.AddressPool, "/")[1])
				if err != nil {
					log.Errorf("error acquiring subnet len. Error: %s", err)
				}
				return uint(p)
			}()
			if isIPv6 {
				// Get first available IPv6 address
				ipAddress, err = netutils.GetSubnetIPv6(subnetIP, subnetLen, "")
				if err != nil {
					log.Errorf("error acquiring subnet ip. Error: %s", err)
					return "", err
				}
			} else {
				// Get first available IPv4 address
				subnetAddr := netutils.GetSubnetAddr(subnetIP, subnetLen)
				ipAddress, err = netutils.GetSubnetIP(subnetAddr, subnetLen, 32, 1)
				if err != nil {
					log.Errorf("error acquiring subnet ip. Error: %s", err)
					return "", err
				}
			}
			// Build the response
			aresp := AddressAllocResponse{
				NetworkID:   allocReq.NetworkID,
				IPv4Address: ipAddress + "/" + fmt.Sprintf("%d", subnetLen),
			}

			return aresp, nil
		}
		log.Errorf("Could not find the network for: %s", allocReq.NetworkID)
		return nil, errors.New("network not found")
	}

	// find the network from network id
	nwCfg := &mastercfg.CfgNetworkState{}
	nwCfg.StateDriver = stateDriver
	err = nwCfg.Read(networkID)
	if err != nil {
		log.Errorf("network %s is not operational", networkID)
		return nil, err
	}

	// Alloc addresses
	addr, err := networkAllocAddress(nwCfg, epgCfg, allocReq.PreferredIPv4Address, netutils.IsIPv6(allocReq.AddressPool))
	if err != nil {
		log.Errorf("Failed to allocate address. Err: %v", err)
		return nil, err
	}

	var subnetLen uint
	if isIPv6 {
		subnetLen = nwCfg.IPv6SubnetLen
	} else {
		subnetLen = nwCfg.SubnetLen
	}

	// Build the response
	aresp := AddressAllocResponse{
		NetworkID:   allocReq.NetworkID,
		IPv4Address: addr + "/" + fmt.Sprintf("%d", subnetLen),
	}

	return aresp, nil
}
1124786
func (na *NetAddress) String() string {
	if na == nil {
		return "<nil-NetAddress>"
	}
	if na.str == "" {
		addrStr := na.DialString()
		if na.ID != "" {
			addrStr = IDAddressString(na.ID, addrStr)
		}
		na.str = addrStr
	}
	return na.str
}
427150
func lookupAddr(ctx context.Context, resolver *net.Resolver, host string) (string, error) {
	// Resolve the IP address or hostname to an IP address.
	addrs, err := resolver.LookupIPAddr(ctx, host)
	if err != nil {
		return "", errors.Wrap(err, "looking up IP addresses")
	}
	if len(addrs) == 0 {
		return "", fmt.Errorf("cannot resolve %q to an address", host)
	}

	// LookupIPAddr() can return a mix of IPv6 and IPv4
	// addresses. Return the first IPv4 address if possible.
	for _, addr := range addrs {
		if ip := addr.IP.To4(); ip != nil {
			return ip.String(), nil
		}
	}

	// No IPv4 address, return the first resolved address instead.
	return addrs[0].String(), nil
}
1036720
func getAddr(addr string) (string, error) {
	if strings.Compare(addr, "0.0.0.0") == 0 {
		addrs, err := net.InterfaceAddrs()
		if err != nil {
			return "", err
		}
		for _, address := range addrs {
			// check the address type and if it is not a loopback the display it
			if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
				if ipnet.IP.To4() != nil {
					return ipnet.IP.String(), nil
				}
			}
		}
	}
	return addr, nil
}
1128526
func IsHexAddress(s string) bool {
	if hasHexPrefix(s) {
		s = s[2:]
	}
	return len(s) == 2*AddressLength && isHex(s)
}
232691
func addressFamilyToString(af uint16) string {
	switch af {
	case syscall.AF_INET:
		return "inet"
	case syscall.AF_INET6:
		return "inet6"
	default:
		return fmt.Sprintf("%d", af)
	}
}
880439
func (hp HostPort) NetAddr() string {
	return net.JoinHostPort(hp.Value, strconv.Itoa(hp.Port))
}
507468
func (addr Address) NetworkAddress() network.Address {
	return network.Address{
		Value:     addr.Value,
		Type:      network.AddressType(addr.Type),
		Scope:     network.Scope(addr.Scope),
		SpaceName: network.SpaceName(addr.SpaceName),
	}
}
455883
func ParseAdvertiseAddr(advertiseIP string) (string, string, error) {
	advertiseIP = strings.TrimSpace(advertiseIP)
	host := advertiseIP
	port := ""
	if len(net.ParseIP(host)) == 0 && strings.Contains(advertiseIP, ":") {
		var err error
		host, port, err = net.SplitHostPort(advertiseIP)
		if err != nil {
			return "", "", trace.BadParameter("failed to parse address %q", advertiseIP)
		}
		if _, err := strconv.Atoi(port); err != nil {
			return "", "", trace.BadParameter("bad port %q, expected integer", port)
		}
		if host == "" {
			return "", "", trace.BadParameter("missing host parameter")
		}
	}
	ip := net.ParseIP(host)
	if len(ip) != 0 {
		if ip.IsUnspecified() || ip.IsMulticast() {
			return "", "", trace.BadParameter("unreachable advertise IP: %v", advertiseIP)
		}
	}
	return host, port, nil
}
1191236
func ProtocolAndAddress(listenAddr string) (string, string) {
	protocol, address := "tcp", listenAddr
	parts := strings.SplitN(address, "://", 2)
	if len(parts) == 2 {
		protocol, address = parts[0], parts[1]
	}
	return protocol, address
}
1154294
func (n *NetAddress) String() string {
	// TODO(roasbeef): use base58?
	pubkey := n.IdentityKey.SerializeCompressed()

	return fmt.Sprintf("%x@%v", pubkey, n.Address)
}
299726
func IDAddressString(id ID, protocolHostPort string) string {
	hostPort := removeProtocolIfDefined(protocolHostPort)
	return fmt.Sprintf("%s@%s", id, hostPort)
}
1080436
func (a Address) String() string {
	if a.Host == "" && a.Port == "" {
		return ""
	}
	scheme := a.Scheme
	if scheme == "" {
		if a.Port == HTTPSPort {
			scheme = "https"
		} else {
			scheme = "http"
		}
	}
	s := scheme
	if s != "" {
		s += "://"
	}
	if a.Port != "" &&
		((scheme == "https" && a.Port != DefaultHTTPSPort) ||
			(scheme == "http" && a.Port != DefaultHTTPPort)) {
		s += net.JoinHostPort(a.Host, a.Port)
	} else {
		s += a.Host
	}
	if a.Path != "" {
		s += a.Path
	}
	return s
}
675925
func (r Network_Component) GetIpAddressBindings() (resp []datatypes.Network_Component_IpAddress, err error) {
	err = r.Session.DoRequest("SoftLayer_Network_Component", "getIpAddressBindings", nil, &r.Options, &resp)
	return
}
579534
func (pair *IPIdentityPair) PrefixString() string {
	var suffix string
	if !pair.IsHost() {
		var ones int
		if pair.Mask == nil {
			if pair.IP.To4() != nil {
				ones = net.IPv4len
			} else {
				ones = net.IPv6len
			}
		} else {
			ones, _ = pair.Mask.Size()
		}
		suffix = fmt.Sprintf("/%d", ones)
	}
	return fmt.Sprintf("%s%s", pair.IP.String(), suffix)
}