Get the IP address based on instance ID.

        If public IP address not found attempt to get private IP.
424379
def _set_instance_ip(self):
        
        try:
            ip_address = self.network.public_ip_addresses.get(
                self.running_instance_id, self.public_ip_name
            ).ip_address
        except Exception:
            try:
                ip_address = self.network.network_interfaces.get(
                    self.running_instance_id, self.nic_name
                ).ip_configurations[0].private_ip_address
            except Exception as error:
                raise AzureCloudException(
                    'Unable to retrieve instance IP address: {0}.'.format(
                        error
                    )
                )

        self.instance_ip = ip_address
889054
def detect(self):
        
        theip = find_ip(family=self.opts_family)
        self.set_current_value(theip)
        return theip
1276352
public PublicIpMetadata getPublicIp(Server serverRef, String publicIp) {
        return this.getPublicIp(idByRef(serverRef), publicIp);
    }
220046
def show_instance(name, call=None):
    '''
    
    '''
    response = _query('grid', 'server/get', args={'name': name})
    ret = {}
    for item in response['list']:
        name = item['name']
        ret[name] = item

        ret[name]['image_info'] = item['image']
        ret[name]['image'] = item['image']['friendlyName']
        ret[name]['size'] = item['ram']['name']
        ret[name]['public_ips'] = [item['ip']['ip']]
        ret[name]['private_ips'] = []
        ret[name]['state_info'] = item['state']
        if 'active' in item['state']['description']:
            ret[name]['state'] = 'RUNNING'
    return ret
1104386
def PublicIPs(self):
		
		if not self.public_ips:  self.public_ips = clc.v2.PublicIPs(server=self,public_ips_lst=self.ip_addresses,session=self.session)

		return(self.public_ips)
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)
662375
def _get_real_instance_if_mismatch(vpc_info, ipaddr, instance, eni):
    
    # Careful! A route may be a black-hole route, which still has instance and
    # ENI information for an instance that doesn't exist anymore. If a host was
    # terminated and a new host got the same IP then this route won't be
    # updated and will keep pointing to a non-existing node. So we find the
    # instance by IP and check that the route really points to this instance.
    inst_id = instance.id if instance else ""
    eni_id  = eni.id if eni else ""
    if ipaddr:
        real_instance, real_eni = \
                        find_instance_and_eni_by_ip(vpc_info, ipaddr)
        if real_instance.id != inst_id  or real_eni.id != eni_id:
            return real_instance
    return None
758635
def getPublicIP():
    """"""
    try:
        # Try to get the internet-facing IP by attempting a connection
        # to a non-existent server and reading what IP was used.
        with closing(socket.socket(socket.AF_INET, socket.SOCK_DGRAM)) as sock:
            # 203.0.113.0/24 is reserved as TEST-NET-3 by RFC 5737, so
            # there is guaranteed to be no one listening on the other
            # end (and we won't accidentally DOS anyone).
            sock.connect(('203.0.113.1', 1))
            ip = sock.getsockname()[0]
        return ip
    except:
        # Something went terribly wrong. Just give loopback rather
        # than killing everything, because this is often called just
        # to provide a default argument
        return '127.0.0.1'
1043454
def get_public_ip_address(ip_address)
      params = {
          'command' => 'listPublicIpAddresses',
          'ipaddress' => ip_address
      }
      json = send_request(params)
      return nil unless json['publicipaddress']
      json['publicipaddress'].first
    end
633615
def associate_public_ip(self, instance_id, public_ip_id, private_ip=None):
        """"""
        floating_ip = self.client.floating_ips.get(public_ip_id)
        floating_ip = floating_ip.to_dict()
        address = floating_ip.get('ip')

        self.client.servers.add_floating_ip(instance_id, address, private_ip)

        return True
269578
def get_or_create_from_ip(ip):
        
        data = ip_api_handler.get(ip)
        if data and any(v for v in data.values()):
            if data.get('ip_address', None) is None or not data['ip_address']:
                data['ip_address'] = ip
            return IPInfo.objects.get_or_create(**data)
        return None, False
868413
def get_server_by_ip(self, ip_address):
        
        data = self.get_request('/ip_address/{0}'.format(ip_address))
        UUID = data['ip_address']['server']
        return self.get_server(UUID)
699855
def _allocate_address(self, instance):
        
        connection = self._connect()
        free_addresses = [ ip for ip in connection.get_all_addresses() if not ip.instance_id]
        if not free_addresses:
            try:
                address = connection.allocate_address()
            except Exception as ex:
                log.error("Unable to allocate a public IP address to instance `%s`",
                          instance.id)
                return None

        try:
            address = free_addresses.pop()
            instance.use_ip(address)
            return address.public_ip
        except Exception as ex:
            log.error("Unable to associate IP address %s to instance `%s`",
                      address, instance.id)
            return None
972971
def _get_ip_public(self, queue_target, url, json=False, key=None):
        """"""
        try:
            response = urlopen(url, timeout=self.timeout).read().decode('utf-8')
        except Exception as e:
            logger.debug("IP plugin - Cannot open URL {} ({})".format(url, e))
            queue_target.put(None)
        else:
            # Request depend on service
            try:
                if not json:
                    queue_target.put(response)
                else:
                    queue_target.put(loads(response)[key])
            except ValueError:
                queue_target.put(None)
844898
def read_address(self, ip_address):
        
        '''
            
        '''
        
        title = '%s.read_address' % self.__class__.__name__

    # validate inputs
        input_fields = {
            'ip_address': ip_address
        }
        for key, value in input_fields.items():
            if value:
                object_title = '%s(%s=%s)' % (title, key, str(value))
                self.fields.validate(value, '.%s' % key, object_title)
    
    # report query
        self.iam.printer('Querying AWS region %s for properties of elastic ip %s.' % (self.iam.region_name, ip_address))
        
    # discover details associated with instance id
        try:
            response = self.connection.describe_addresses(PublicIps=[ ip_address ])
            address_info = response['Addresses'][0]
        except:
            raise AWSConnectionError(title)

    # create dictionary of instance details
        address_details = {
            'instance_id': '',
            'public_ip': '',
            'allocation_id': '',
            'association_id': '',
            'domain': '',
            'network_interface_id': '',
            'network_interface_owner_id': '',
            'private_ip_address': '',
            'tags': [],
            'region': self.iam.region_name
        }
        address_details = self.iam.ingest(address_info, address_details)

        return address_details
777697
public static String getPrivateIp(InstanceInfo instanceInfo) {
        String defaultPrivateIp = null;
        if (instanceInfo.getDataCenterInfo() instanceof AmazonInfo) {
            defaultPrivateIp = ((AmazonInfo) instanceInfo.getDataCenterInfo()).get(AmazonInfo.MetaDataKey.localIpv4);
        }

        if (isNullOrEmpty(defaultPrivateIp)) {
            // no other information, best effort
            defaultPrivateIp = instanceInfo.getIPAddr();
        }

        return defaultPrivateIp;
    }
86846
def _is_private_ip(ip):
	
	networks = [
		"0.0.0.0/8",
		"10.0.0.0/8",
		"100.64.0.0/10",
		"127.0.0.0/8",
		"169.254.0.0/16",
		"172.16.0.0/12",
		"192.0.0.0/24",
		"192.0.2.0/24",
		"192.88.99.0/24",
		"192.168.0.0/16",
		"198.18.0.0/15",
		"198.51.100.0/24",
		"203.0.113.0/24",
		"240.0.0.0/4",
		"255.255.255.255/32",
		"224.0.0.0/4",
	]

	for network in networks:
		try:
			ipaddr = struct.unpack(">I", socket.inet_aton(ip))[0]

			netaddr, bits = network.split("/")

			network_low = struct.unpack(">I", socket.inet_aton(netaddr))[0]
			network_high = network_low | 1 << (32 - int(bits)) - 1

			if ipaddr <= network_high and ipaddr >= network_low:
				return True
		except Exception:
			continue

	return False