Return the first net_interface.%d.ip for a system in a public/private network.
545526
def __getIP(self, public):
        """"""

        maybeNot = (lambda x: x) if public else (lambda x: not x)
        nets_id = [net.id for net in self.networks if maybeNot(net.isPublic())]
        for s in self.systems:
            i = 0
            while True:
                value = s.getValue("net_interface.%d.connection" % i)
                if not value:
                    break
                if value in nets_id:
                    ip = s.getValue("net_interface.%d.ip" % i)
                    if ip:
                        return ip
                i += 1
        return None
606340
def get_ip_on_same_subnet(self, other_compute):
        
        if other_compute == self:
            return (self.host_ip, self.host_ip)

        # Perhaps the user has correct network gateway, we trust him
        if (self.host_ip not in ('0.0.0.0', '127.0.0.1') and other_compute.host_ip not in ('0.0.0.0', '127.0.0.1')):
            return (self.host_ip, other_compute.host_ip)

        this_compute_interfaces = yield from self.interfaces()
        other_compute_interfaces = yield from other_compute.interfaces()

        # Sort interface to put the compute host in first position
        # we guess that if user specified this host it could have a reason (VMware Nat / Host only interface)
        this_compute_interfaces = sorted(this_compute_interfaces, key=lambda i: i["ip_address"] != self.host_ip)
        other_compute_interfaces = sorted(other_compute_interfaces, key=lambda i: i["ip_address"] != other_compute.host_ip)

        for this_interface in this_compute_interfaces:
            # Skip if no ip or no netmask (vbox when stopped set a null netmask)
            if len(this_interface["ip_address"]) == 0 or this_interface["netmask"] is None:
                continue
            # Ignore 169.254 network because it's for Windows special purpose
            if this_interface["ip_address"].startswith("169.254."):
                continue

            this_network = ipaddress.ip_network("{}/{}".format(this_interface["ip_address"], this_interface["netmask"]), strict=False)

            for other_interface in other_compute_interfaces:
                if len(other_interface["ip_address"]) == 0 or other_interface["netmask"] is None:
                    continue

                # Avoid stuff like 127.0.0.1
                if other_interface["ip_address"] == this_interface["ip_address"]:
                    continue

                other_network = ipaddress.ip_network("{}/{}".format(other_interface["ip_address"], other_interface["netmask"]), strict=False)
                if this_network.overlaps(other_network):
                    return (this_interface["ip_address"], other_interface["ip_address"])

        raise ValueError("No common subnet for compute {} and {}".format(self.name, other_compute.name))
657328
def get_my_ip():
    """"""
    ip = subprocess.check_output(GET_IP_CMD, shell=True).decode('utf-8')[:-1]
    return ip.strip()
1177430
def Get(self,key):
		""""""

		for public_ip in self.public_ips:
			if public_ip.id == key:  return(public_ip)
			elif key == public_ip.internal:  return(public_ip)
121194
def ip(args):
    
    if len(args) != 0:
        sys.exit(not p.print_help())

    s = InstanceSkeleton()
    print("IP address:", s.private_ip_address, file=sys.stderr)
    print("Instance type:", s.instance_type, file=sys.stderr)
1141882
def _get_interface(self, name):
        """"""
        return proxy_new(
            self.connection,
            Gio.DBusProxyFlags.DO_NOT_LOAD_PROPERTIES |
            Gio.DBusProxyFlags.DO_NOT_CONNECT_SIGNALS,
            info=None,
            name=self.bus_name,
            object_path=self.object_path,
            interface_name=name,
        )
143328
private static String getFirstIp(String ip) {
		if (ip != null) {
			final int indexOfFirstComma = ip.indexOf(',');
			if (indexOfFirstComma != -1) {
				ip = ip.substring(0, indexOfFirstComma);
			}
		}
		return ip;
	}
1185806
def get_public_network_ip(ips, public_subnet):
    
    for ip in ips:
        if net.ip_in_subnet(ip, public_subnet):
            return ip
    msg = "IPs (%s) are not valid for any of subnet specified %s" % (str(ips), str(public_subnet))
    raise RuntimeError(msg)
662141
def get_interfaces_ip(self):
        """"""
        interfaces_ip = {}

        interface_table = junos_views.junos_ip_interfaces_table(self.device)
        interface_table.get()
        interface_table_items = interface_table.items()

        _FAMILY_VMAP_ = {
            "inet": "ipv4",
            "inet6": "ipv6"
            # can add more mappings
        }
        _FAMILY_MAX_PREFIXLEN = {"inet": 32, "inet6": 128}

        for interface_details in interface_table_items:
            ip_network = interface_details[0]
            ip_address = ip_network.split("/")[0]
            address = napalm.base.helpers.convert(
                napalm.base.helpers.ip, ip_address, ip_address
            )
            try:
                interface_details_dict = dict(interface_details[1])
                family_raw = interface_details_dict.get("family")
                interface = py23_compat.text_type(
                    interface_details_dict.get("interface")
                )
            except ValueError:
                continue
            prefix = napalm.base.helpers.convert(
                int, ip_network.split("/")[-1], _FAMILY_MAX_PREFIXLEN.get(family_raw)
            )
            family = _FAMILY_VMAP_.get(family_raw)
            if not family or not interface:
                continue
            if interface not in interfaces_ip.keys():
                interfaces_ip[interface] = {}
            if family not in interfaces_ip[interface].keys():
                interfaces_ip[interface][family] = {}
            if address not in interfaces_ip[interface][family].keys():
                interfaces_ip[interface][family][address] = {}
            interfaces_ip[interface][family][address]["prefix_length"] = prefix

        return interfaces_ip
106039
def get_lan_ip(interface="default"):
    if sys.version_info < (3, 0, 0):
        if type(interface) == str:
            interface = unicode(interface)
    else:
        if type(interface) == bytes:
            interface = interface.decode("utf-8")

    # Get ID of interface that handles WAN stuff.
    default_gateway = get_default_gateway(interface)
    gateways = netifaces.gateways()
    wan_id = None
    if netifaces.AF_INET in gateways:
        gw_list = gateways[netifaces.AF_INET]
        for gw_info in gw_list:
            if gw_info[0] == default_gateway:
                wan_id = gw_info[1]
                break

    # Find LAN IP of interface for WAN stuff.
    interfaces = netifaces.interfaces()
    if wan_id in interfaces:
        families = netifaces.ifaddresses(wan_id)
        if netifaces.AF_INET in families:
            if_info_list = families[netifaces.AF_INET]
            for if_info in if_info_list:
                if "addr" in if_info:
                    return if_info["addr"]

    
    if platform.system() == "Linux":
        if ip is not None:
            return ip.routes["8.8.8.8"]["prefsrc"]

    return None
599073
def get_my_ips():
    """"""
    ips = list()
    if not os.path.exists("/sys/class/net"): # not linux
        return ['127.0.0.1']
    for ifdev in os.listdir("/sys/class/net"):
        if ifdev == "lo":
            continue
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            ips.append(socket.inet_ntoa(fcntl.ioctl(
                sock.fileno(),
                0x8915,  # SIOCGIFADDR
                struct.pack('256s', ifdev[:15].encode())
            )[20:24]))
        except OSError:
            pass
    return ips
668894
def ip_lookup(self, ip_address):
        
        obj = self.client['Network_Subnet_IpAddress']
        return obj.getByIpAddress(ip_address, mask='hardware, virtualGuest')
1284517
def _get_network_interface(name, resource_group):
    '''
    
    '''
    public_ips = []
    private_ips = []
    netapi_versions = get_api_versions(kwargs={
        'resource_provider': 'Microsoft.Network',
        'resource_type': 'publicIPAddresses'
        }
    )
    netapi_version = netapi_versions[0]
    netconn = get_conn(client_type='network')
    netiface_query = netconn.network_interfaces.get(
        resource_group_name=resource_group,
        network_interface_name=name
    )

    netiface = netiface_query.as_dict()
    for index, ip_config in enumerate(netiface['ip_configurations']):
        if ip_config.get('private_ip_address') is not None:
            private_ips.append(ip_config['private_ip_address'])
        if 'id' in ip_config.get('public_ip_address', {}):
            public_ip_name = get_resource_by_id(
                ip_config['public_ip_address']['id'],
                netapi_version,
                'name'
            )
            public_ip = _get_public_ip(public_ip_name, resource_group)
            public_ips.append(public_ip['ip_address'])
            netiface['ip_configurations'][index]['public_ip_address'].update(public_ip)

    return netiface, public_ips, private_ips
406732
def get_server_public_ip(server, cached_rules=nil, cached_nat=nil)
      return nil unless server
      # find the public ip
      nic = get_server_default_nic(server)

      ssh_rule = get_ssh_port_forwarding_rule(server, cached_rules)
      return ssh_rule['ipaddress'] if ssh_rule

      winrm_rule = get_winrm_port_forwarding_rule(server, cached_rules)
      return winrm_rule['ipaddress'] if winrm_rule

      #check for static NAT
      if cached_nat
        ip_addr = cached_nat.find {|v| v['virtualmachineid'] == server['id']}
      else
        ip_addr = list_public_ip_addresses.find {|v| v['virtualmachineid'] == server['id']}
      end
      if ip_addr
        return ip_addr['ipaddress']
      end
      if nic.empty?
        return []
      end
      nic['ipaddress'] || []
    end
911989
def GetForwardedIps(self, interface, interface_ip=None):
    
    try:
      ips = netifaces.ifaddresses(interface)
      ips = ips[netifaces.AF_INET]
    except (ValueError, IndexError):
      return []
    forwarded_ips = []
    for ip in ips:
      if ip['addr'] != interface_ip:
        full_addr = '%s/%d' % (ip['addr'], netaddr.IPAddress(ip['netmask']).netmask_bits())
        forwarded_ips.append(full_addr)
    return self.ParseForwardedIps(forwarded_ips)
510654
def _interfaces_ip(out):
    
    ret = dict()

    def parse_network(value, cols):
        """
        Return a tuple of ip, netmask, broadcast
        based on the current set of cols
        """
        brd = None
        if '/' in value:  # we have a CIDR in this address
            ip, cidr = value.split('/')  # pylint: disable=C0103
        else:
            ip = value  # pylint: disable=C0103
            cidr = 32

        if type_ == 'inet':
            mask = cidr_to_ipv4_netmask(int(cidr))
            if 'brd' in cols:
                brd = cols[cols.index('brd') + 1]
        elif type_ == 'inet6':
            mask = cidr
        return (ip, mask, brd)

    groups = re.compile('\r?\n\\d').split(out)
    for group in groups:
        iface = None
        data = dict()

        for line in group.splitlines():
            if ' ' not in line:
                continue
            match = re.match(r'^\d*:\s+([\w.\-]+)(?:@)?([\w.\-]+)?:\s+<(.+)>', line)
            if match:
                iface, parent, attrs = match.groups()
                if 'UP' in attrs.split(','):
                    data['up'] = True
                else:
                    data['up'] = False
                if parent:
                    data['parent'] = parent
                continue

            cols = line.split()
            if len(cols) >= 2:
                type_, value = tuple(cols[0:2])
                iflabel = cols[-1:][0]
                if type_ in ('inet', 'inet6'):
                    if 'secondary' not in cols:
                        ipaddr, netmask, broadcast = parse_network(value, cols)
                        if type_ == 'inet':
                            if 'inet' not in data:
                                data['inet'] = list()
                            addr_obj = dict()
                            addr_obj['address'] = ipaddr
                            addr_obj['netmask'] = netmask
                            addr_obj['broadcast'] = broadcast
                            addr_obj['label'] = iflabel
                            data['inet'].append(addr_obj)
                        elif type_ == 'inet6':
                            if 'inet6' not in data:
                                data['inet6'] = list()
                            addr_obj = dict()
                            addr_obj['address'] = ipaddr
                            addr_obj['prefixlen'] = netmask
                            data['inet6'].append(addr_obj)
                    else:
                        if 'secondary' not in data:
                            data['secondary'] = list()
                        ip_, mask, brd = parse_network(value, cols)
                        data['secondary'].append({
                            'type': type_,
                            'address': ip_,
                            'netmask': mask,
                            'broadcast': brd,
                            'label': iflabel,
                        })
                        del ip_, mask, brd
                elif type_.startswith('link'):
                    data['hwaddr'] = value
        if iface:
            ret[iface] = data
            del iface, data
    return ret
1362633
def _get_ip():
    
    cmd_netstat = ['netstat', '-nr']
    p1 = subprocess.Popen(cmd_netstat, stdout=subprocess.PIPE)
    cmd_grep = ['grep', '^0\.0\.0\.0']
    p2 = subprocess.Popen(cmd_grep, stdin=p1.stdout, stdout=subprocess.PIPE)
    cmd_awk = ['awk', '{ print $2 }']
    p3 = subprocess.Popen(cmd_awk, stdin=p2.stdout, stdout=subprocess.PIPE)
    galaxy_ip = p3.stdout.read()
    log.debug('Host IP determined to be %s', galaxy_ip)
    return galaxy_ip