// GetExternalAddress recovers the external address masking the
// subjacent network
187238
func GetExternalAddress() ExternalAddress {
	ip, err := GetMyIP()
	if err != nil {
		Logln("Can't get my external IP.", err)
		panic(err)
	}
	return ExternalAddress(ip)
}
353944
func (pf *PortForwarder) listenOnPortAndAddress(port *ForwardedPort, protocol string, address string) error {
	listener, err := pf.getListener(protocol, address, port)
	if err != nil {
		return err
	}
	pf.listeners = append(pf.listeners, listener)
	go pf.waitForConnection(listener, *port)
	return nil
}
1232476
func (peers Peers) SearchByExternalAddress(addr ExternalAddress) (*Peer, error) {
	for _, peer := range peers {
		if peer.HasAddr(addr) {
			return peer, nil
		}
	}
	return nil, errors.New("Peer not found.")
}
1247088
func (h *emptyHandle) GetLocalAddresses(dev, filterDev string) (sets.String, error) {
	return nil, fmt.Errorf("netlink is not supported in this platform")
}
1258061
func (d *MasterDaemon) getPluginAddress(hostName string) (string, error) {
	srvList, err := d.objdbClient.GetService("netplugin.vtep")
	if err != nil {
		log.Errorf("Error getting netplugin nodes. Err: %v", err)
		return "", err
	}

	for _, srv := range srvList {
		if srv.Hostname == hostName {
			return srv.HostAddr, nil
		}
	}

	return "", fmt.Errorf("Could not find plugin instance with name: %s", hostName)
}
996150
func (c *CheckRun) GetExternalID() string {
	if c == nil || c.ExternalID == nil {
		return ""
	}
	return *c.ExternalID
}
1070759
func deserializeImportedAddress(row *dbAddressRow) (*dbImportedAddressRow, error) {
	// The serialized imported address raw data format is:
	//   <encpubkeylen><encpubkey><encprivkeylen><encprivkey>
	//
	// 4 bytes encrypted pubkey len + encrypted pubkey + 4 bytes encrypted
	// privkey len + encrypted privkey

	// Given the above, the length of the entry must be at a minimum
	// the constant value sizes.
	if len(row.rawData) < 8 {
		str := "malformed serialized imported address"
		return nil, managerError(ErrDatabase, str, nil)
	}

	retRow := dbImportedAddressRow{
		dbAddressRow: *row,
	}

	pubLen := binary.LittleEndian.Uint32(row.rawData[0:4])
	retRow.encryptedPubKey = make([]byte, pubLen)
	copy(retRow.encryptedPubKey, row.rawData[4:4+pubLen])
	offset := 4 + pubLen
	privLen := binary.LittleEndian.Uint32(row.rawData[offset : offset+4])
	offset += 4
	retRow.encryptedPrivKey = make([]byte, privLen)
	copy(retRow.encryptedPrivKey, row.rawData[offset:offset+privLen])

	return &retRow, nil
}
532598
func (e *endpoint) GetRemoteAddress() (tcpip.FullAddress, *tcpip.Error) {
	e.mu.RLock()
	defer e.mu.RUnlock()

	if e.state != stateConnected {
		return tcpip.FullAddress{}, tcpip.ErrNotConnected
	}

	return tcpip.FullAddress{
		Addr: e.id.RemoteAddress,
		Port: e.id.RemotePort,
		NIC:  e.boundNICID,
	}, nil
}
688993
func networkAllocAddress(nwCfg *mastercfg.CfgNetworkState, epgCfg *mastercfg.EndpointGroupState,
	reqAddr string, isIPv6 bool) (string, error) {
	var ipAddress string
	var ipAddrValue uint
	var found bool
	var err error
	var hostID string

	// alloc address
	if reqAddr == "" {
		if isIPv6 {
			// Get the next available IPv6 address
			hostID, err = netutils.GetNextIPv6HostID(nwCfg.IPv6LastHost, nwCfg.IPv6Subnet, nwCfg.IPv6SubnetLen, nwCfg.IPv6AllocMap)
			if err != nil {
				log.Errorf("create eps: error allocating ip. Error: %s", err)
				return "", err
			}
			ipAddress, err = netutils.GetSubnetIPv6(nwCfg.IPv6Subnet, nwCfg.IPv6SubnetLen, hostID)
			if err != nil {
				log.Errorf("create eps: error acquiring subnet ip. Error: %s", err)
				return "", err
			}
			nwCfg.IPv6LastHost = hostID
			netutils.ReserveIPv6HostID(hostID, &nwCfg.IPv6AllocMap)
		} else {
			if epgCfg != nil && len(epgCfg.IPPool) > 0 { // allocate from epg network
				log.Infof("allocating ip address from epg pool %s", epgCfg.IPPool)
				ipAddrValue, found = netutils.NextClear(epgCfg.EPGIPAllocMap, 0, nwCfg.SubnetLen)
				if !found {
					log.Errorf("auto allocation failed - address exhaustion in pool %s",
						epgCfg.IPPool)
					err = core.Errorf("auto allocation failed - address exhaustion in pool %s",
						epgCfg.IPPool)
					return "", err
				}
				ipAddress, err = netutils.GetSubnetIP(nwCfg.SubnetIP, nwCfg.SubnetLen, 32, ipAddrValue)
				if err != nil {
					log.Errorf("create eps: error acquiring subnet ip. Error: %s", err)
					return "", err
				}
				epgCfg.EPGIPAllocMap.Set(ipAddrValue)
			} else {
				ipAddrValue, found = netutils.NextClear(nwCfg.IPAllocMap, 0, nwCfg.SubnetLen)
				if !found {
					log.Errorf("auto allocation failed - address exhaustion in subnet %s/%d",
						nwCfg.SubnetIP, nwCfg.SubnetLen)
					err = core.Errorf("auto allocation failed - address exhaustion in subnet %s/%d",
						nwCfg.SubnetIP, nwCfg.SubnetLen)
					return "", err
				}
				ipAddress, err = netutils.GetSubnetIP(nwCfg.SubnetIP, nwCfg.SubnetLen, 32, ipAddrValue)
				if err != nil {
					log.Errorf("create eps: error acquiring subnet ip. Error: %s", err)
					return "", err
				}
				nwCfg.IPAllocMap.Set(ipAddrValue)
			}
		}

		// Docker, Mesos issue a Alloc Address first, followed by a CreateEndpoint
		// Kubernetes issues a create endpoint directly
		// since networkAllocAddress is called from both AllocAddressHandler and CreateEndpointHandler,
		// we need to make sure that the EpCount is incremented only when we are allocating
		// a new IP. In case of Docker, Mesos CreateEndPoint will already request a IP that
		// allocateAddress had allocated in the earlier call.
		nwCfg.EpAddrCount++

	} else if reqAddr != "" && nwCfg.SubnetIP != "" {
		if isIPv6 {
			hostID, err = netutils.GetIPv6HostID(nwCfg.IPv6Subnet, nwCfg.IPv6SubnetLen, reqAddr)
			if err != nil {
				log.Errorf("create eps: error getting host id from hostIP %s Subnet %s/%d. Error: %s",
					reqAddr, nwCfg.IPv6Subnet, nwCfg.IPv6SubnetLen, err)
				return "", err
			}
			netutils.ReserveIPv6HostID(hostID, &nwCfg.IPv6AllocMap)
		} else {

			if epgCfg != nil && len(epgCfg.IPPool) > 0 { // allocate from epg network
				ipAddrValue, err = netutils.GetIPNumber(nwCfg.SubnetIP, nwCfg.SubnetLen, 32, reqAddr)
				if err != nil {
					log.Errorf("create eps: error getting host id from hostIP %s pool %s. Error: %s",
						reqAddr, epgCfg.IPPool, err)
					return "", err
				}
				epgCfg.EPGIPAllocMap.Set(ipAddrValue)
			} else {
				ipAddrValue, err = netutils.GetIPNumber(nwCfg.SubnetIP, nwCfg.SubnetLen, 32, reqAddr)
				if err != nil {
					log.Errorf("create eps: error getting host id from hostIP %s Subnet %s/%d. Error: %s",
						reqAddr, nwCfg.SubnetIP, nwCfg.SubnetLen, err)
					return "", err
				}
				nwCfg.IPAllocMap.Set(ipAddrValue)
			}
		}

		ipAddress = reqAddr
	}

	if epgCfg != nil && len(epgCfg.IPPool) > 0 {
		err = epgCfg.Write()
		if err != nil {
			log.Errorf("error writing epg config. Error: %s", err)
			return "", err
		}
	}

	err = nwCfg.Write()
	if err != nil {
		log.Errorf("error writing nw config. Error: %s", err)
		return "", err
	}

	return ipAddress, nil
}
588490
func (g *Cloud) getNetworkTierFromAddress(name, region string) (string, error) {
	if !g.AlphaFeatureGate.Enabled(AlphaFeatureNetworkTiers) {
		return cloud.NetworkTierDefault.ToGCEValue(), nil
	}
	addr, err := g.GetAlphaRegionAddress(name, region)
	if err != nil {
		return handleAlphaNetworkTierGetError(err)
	}
	return addr.NetworkTier, nil
}
635572
func (c *Cluster) GetListenAddress() string {
	c.mu.RLock()
	defer c.mu.RUnlock()
	if c.nr != nil {
		return c.nr.config.ListenAddr
	}
	return ""
}
1006350
func (r Network_Vlan) GetTotalPrimaryIpAddressCount() (resp uint, err error) {
	err = r.Session.DoRequest("SoftLayer_Network_Vlan", "getTotalPrimaryIpAddressCount", nil, &r.Options, &resp)
	return
}
1188709
func getAddress(args ...interface{}) string {
	var host string
	var port int

	if len(args) == 1 {
		switch arg := args[0].(type) {
		case string:
			addrs := strings.Split(args[0].(string), ":")
			if len(addrs) == 1 {
				host = addrs[0]
			} else if len(addrs) >= 2 {
				host = addrs[0]
				_port, _ := strconv.ParseInt(addrs[1], 10, 0)
				port = int(_port)
			}
		case int:
			port = arg
		}
	} else if len(args) >= 2 {
		if arg, ok := args[0].(string); ok {
			host = arg
		}
		if arg, ok := args[1].(int); ok {
			port = arg
		}
	}

	if envHost := os.Getenv("HOST"); len(envHost) != 0 {
		host = envHost
	} else if len(host) == 0 {
		host = "0.0.0.0"
	}

	if envPort, _ := strconv.ParseInt(os.Getenv("PORT"), 10, 32); envPort != 0 {
		port = int(envPort)
	} else if port == 0 {
		port = 8000
	}

	addr := host + ":" + strconv.FormatInt(int64(port), 10)

	return addr
}
921620
func getNodeExternalIP(node *api.Node) string {
	for _, address := range node.Status.Addresses {
		if address.Type == api.NodeExternalIP {
			return address.Address
		}
	}

	return "<none>"
}
776898
func GetHostPrimaryAddress(node *models.NodeStatus) *models.PathStatus {
	if node.Host == nil {
		return nil
	}

	return node.Host.PrimaryAddress
}
642355
func GetSandboxForExternalKey(basePath string, key string) (Sandbox, error) {
	if err := createNamespaceFile(key); err != nil {
		return nil, err
	}

	if err := mountNetworkNamespace(basePath, key); err != nil {
		return nil, err
	}
	n := &networkNamespace{path: key, nextIfIndex: make(map[string]int)}

	sboxNs, err := netns.GetFromPath(n.path)
	if err != nil {
		return nil, fmt.Errorf("failed get network namespace %q: %v", n.path, err)
	}
	defer sboxNs.Close()

	n.nlHandle, err = netlink.NewHandleAt(sboxNs, syscall.NETLINK_ROUTE)
	if err != nil {
		return nil, fmt.Errorf("failed to create a netlink handle: %v", err)
	}

	err = n.nlHandle.SetSocketTimeout(ns.NetlinkSocketsTimeout)
	if err != nil {
		logrus.Warnf("Failed to set the timeout on the sandbox netlink handle sockets: %v", err)
	}

	// As starting point, disable IPv6 on all interfaces
	err = setIPv6(n.path, "all", false)
	if err != nil {
		logrus.Warnf("Failed to disable IPv6 on all interfaces on network namespace %q: %v", n.path, err)
	}

	if err = n.loopbackUp(); err != nil {
		n.nlHandle.Delete()
		return nil, err
	}

	return n, 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
}