// GetInterfaceIPAddress attempts to find the IP address based on interface name
970940
func GetInterfaceIPAddress(_interface string) (string, error) {
	output, err := exec.Command("/sbin/ip", "-4", "-o", "addr").Output()
	if err != nil {
		return "", err
	}

	for _, line := range strings.Split(string(output), "\n") {
		fields := strings.Fields(line)
		if len(fields) < 4 {
			continue
		}

		if strings.HasPrefix(fields[1], _interface) {
			return strings.Split(fields[3], "/")[0], nil
		}
	}

	return "", fmt.Errorf("Unable to find ip for interface: %s", _interface)
}
1003229
func GetAllInterfaces() (IfAddrs, error) {
	ifs, err := net.Interfaces()
	if err != nil {
		return nil, err
	}

	ifAddrs := make(IfAddrs, 0, len(ifs))
	for _, intf := range ifs {
		addrs, err := intf.Addrs()
		if err != nil {
			return nil, err
		}

		for _, addr := range addrs {
			var ipAddr IPAddr
			ipAddr, err = NewIPAddr(addr.String())
			if err != nil {
				return IfAddrs{}, fmt.Errorf("unable to create an IP address from %q", addr.String())
			}

			ifAddr := IfAddr{
				SockAddr:  ipAddr,
				Interface: intf,
			}
			ifAddrs = append(ifAddrs, ifAddr)
		}
	}

	return ifAddrs, nil
}
79453
func getIP(r *http.Request) string {
	var addr string

	if fwd := r.Header.Get(xForwardedFor); fwd != "" {
		// Only grab the first (client) address. Note that '192.168.0.1,
		// 10.1.1.1' is a valid key for X-Forwarded-For where addresses after
		// the first may represent forwarding proxies earlier in the chain.
		s := strings.Index(fwd, ", ")
		if s == -1 {
			s = len(fwd)
		}
		addr = fwd[:s]
	} else if fwd := r.Header.Get(xRealIP); fwd != "" {
		// X-Real-IP should only contain one IP address (the client making the
		// request).
		addr = fwd
	} else if fwd := r.Header.Get(forwarded); fwd != "" {
		// match should contain at least two elements if the protocol was
		// specified in the Forwarded header. The first element will always be
		// the 'for=' capture, which we ignore. In the case of multiple IP
		// addresses (for=8.8.8.8, 8.8.4.4,172.16.1.20 is valid) we only
		// extract the first, which should be the client IP.
		if match := forRegex.FindStringSubmatch(fwd); len(match) > 1 {
			// IPv6 addresses in Forwarded headers are quoted-strings. We strip
			// these quotes.
			addr = strings.Trim(match[1], `"`)
		}
	}

	return addr
}
1092100
func getIPResources(hostID string, hostIP string, staticIPs ...string) ([]HostIPResource, error) {

	//make a map of all ipaddresses to interface
	ifacemap, err := getInterfaceMap()
	if err != nil {
		return nil, err
	}
	hostLogger := plog.WithFields(log.Fields{
		"hostid": hostID,
		"hostip": hostIP,
	})
	hostLogger.WithFields(log.Fields{
		"interfaces": ifacemap,
	}).Debug("Interfaces on this host")

	// Get a unique list of ips from staticIPs and hostIP.
	ips := func() []string {
		for _, ip := range staticIPs {
			if hostIP == ip {
				return staticIPs
			}
		}
		return append(staticIPs, hostIP)
	}()

	hostIPResources := make([]HostIPResource, len(ips))
	for i, ip := range ips {
		hostLogger.WithFields(log.Fields{
			"ip": ip,
		}).Debug("Checking IP")
		if iface, ok := ifacemap[ip]; ok {
			if isLoopBack(ip) {
				return nil, IsLoopbackError(ip)
			}
			hostIPResource := HostIPResource{
				HostID:        hostID,
				IPAddress:     ip,
				InterfaceName: iface.Name,
				MACAddress:    iface.HardwareAddr.String(),
			}
			hostIPResources[i] = hostIPResource
		} else {
			return nil, InvalidIPAddress(ip)
		}
	}

	return hostIPResources, nil
}
912761
func GetPublicIPv6() ([]*net.IPAddr, error) {
	addresses, err := net.InterfaceAddrs()
	if err != nil {
		return nil, fmt.Errorf("Failed to get interface addresses: %v", err)
	}

	var addrs []*net.IPAddr
	for _, rawAddr := range addresses {
		var ip net.IP
		switch addr := rawAddr.(type) {
		case *net.IPAddr:
			ip = addr.IP
		case *net.IPNet:
			ip = addr.IP
		default:
			continue
		}
		if ip.To4() != nil {
			continue
		}
		if isPrivate(ip) {
			continue
		}
		addrs = append(addrs, &net.IPAddr{IP: ip})
	}
	return addrs, nil
}
1055801
func InterfaceIPs(device string) (ips []net.IP, _ error) {
	var networks []net.Addr

	if iface, err := net.InterfaceByName(device); err != nil {
		return nil, err
	} else if networks, err = iface.Addrs(); err != nil {
		return nil, err
	}

	for _, network := range networks {
		if ipNet, castable := network.(*net.IPNet); castable {
			ips = append(ips, ipNet.IP)
		}
	}

	// Note that on non-IP interfaces it will be an empty slice
	// and no error indicator. Maybe that's not super-perfect.
	return ips, nil
}
1146293
func (mi *maas1Instance) interfaceAddresses(ctx context.ProviderCallContext) ([]network.Address, error) {
	// Fetch a fresh copy of the instance JSON first.
	obj, err := refreshMAASObject(mi.maasObject)
	if err != nil {
		common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
		return nil, errors.Annotate(err, "getting instance details")
	}

	subnetsMap, err := mi.environ.subnetToSpaceIds(ctx)
	if err != nil {
		return nil, errors.Trace(err)
	}
	// Get all the interface details and extract the addresses.
	interfaces, err := maasObjectNetworkInterfaces(ctx, &obj, subnetsMap)
	if err != nil {
		return nil, errors.Trace(err)
	}

	var addresses []network.Address
	for _, iface := range interfaces {
		if iface.Address.Value != "" {
			logger.Debugf("found address %q on interface %q", iface.Address, iface.InterfaceName)
			addresses = append(addresses, iface.Address)
		} else {
			logger.Infof("no address found on interface %q", iface.InterfaceName)
		}
	}
	return addresses, nil
}
133247
func (e Endpoints) GetAddress(ctx context.Context, profileID string, addressID string) (Address, error) {
	request := getAddressRequest{ProfileID: profileID, AddressID: addressID}
	response, err := e.GetAddressEndpoint(ctx, request)
	if err != nil {
		return Address{}, err
	}
	resp := response.(getAddressResponse)
	return resp.Address, resp.Err
}
1006350
func (r Network_Vlan) GetTotalPrimaryIpAddressCount() (resp uint, err error) {
	err = r.Session.DoRequest("SoftLayer_Network_Vlan", "getTotalPrimaryIpAddressCount", nil, &r.Options, &resp)
	return
}
365212
func GetIfaceAddr(name string) (net.Addr, []net.Addr, error) {
	iface, err := net.InterfaceByName(name)
	if err != nil {
		return nil, nil, err
	}
	addrs, err := iface.Addrs()
	if err != nil {
		return nil, nil, err
	}
	var addrs4 []net.Addr
	var addrs6 []net.Addr
	for _, addr := range addrs {
		ip := (addr.(*net.IPNet)).IP
		if ip4 := ip.To4(); ip4 != nil {
			addrs4 = append(addrs4, addr)
		} else if ip6 := ip.To16(); len(ip6) == net.IPv6len {
			addrs6 = append(addrs6, addr)
		}
	}
	switch {
	case len(addrs4) == 0:
		return nil, nil, fmt.Errorf("Interface %v has no IPv4 addresses", name)
	case len(addrs4) > 1:
		fmt.Printf("Interface %v has more than 1 IPv4 address. Defaulting to using %v\n",
			name, (addrs4[0].(*net.IPNet)).IP)
	}
	return addrs4[0], addrs6, nil
}
938327
func (context *BaseContext) GetInterface(
	key string, defaultValue ...interface{}) interface{} {
	if value, ok := context.userData[key]; ok {
		return value
	}
	if len(defaultValue) > 0 {
		return defaultValue[0]
	}
	return nil
}
333500
func (n *NFS) IPAddress() string {
	if len(n.Remark.Servers) < 1 {
		return ""
	}

	v, ok := n.Remark.Servers[0].(map[string]interface{})
	if !ok {
		return ""
	}

	if ip, ok := v["IPAddress"]; ok {
		return ip.(string)
	}
	return ""
}
840184
func (r Virtual_Guest_Network_Component) GetIpAddressBindings() (resp []datatypes.Virtual_Guest_Network_Component_IpAddress, err error) {
	err = r.Session.DoRequest("SoftLayer_Virtual_Guest_Network_Component", "getIpAddressBindings", nil, &r.Options, &resp)
	return
}
720715
func getAddressTypeIP(ip net.IP, addressType string) string {
	if addressType != "" {
		return addressType
	}
	if ip == nil {
		return addrTypeIPv4
	}
	switch ip.To4() {
	case nil:
		return addrTypeIPv6
	default:
		return addrTypeIPv4
	}
}
379141
func (s *Server) CIDRIPAddress() string {
	ip, maskLen := s.IPAddress(), s.NetworkMaskLen()
	if ip != "" && maskLen > 0 {
		return fmt.Sprintf("%s/%d", ip, maskLen)
	}
	return ""
}
423051
func getClientIP(client *http.Client, debug bool) (addr string, err error) {
	resp, err := client.Get(getIPURL)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	clientIP, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	if debug {
		log.Println("Client IP:", string(clientIP))
	}
	return string(clientIP), nil
}
76216
func findInterfaceNetwork(pIface *net.Interface, ip net.IP) (*net.Interface, *net.IPNet, error) {
	ifaces, err := vlanInterfaces(pIface)
	ifaces = append(ifaces, pIface)
	if err != nil {
		return nil, nil, err
	}
	for _, iface := range ifaces {
		if network, _ := findNetwork(iface, ip); network != nil {
			return iface, network, nil
		}
	}
	return nil, nil, fmt.Errorf("Failed to find IP %v on any interface", ip)
}