Individuazione degli indirizzi IP per un'istanza

Scopri come individuare elementi esterni e interni indirizzi IP per l'istanza.

Prima di iniziare

  • Se non l'hai già fatto, configura l'autenticazione. Autenticazione è Il processo di verifica dell'identità per l'accesso ai servizi e alle API di Google Cloud. Per eseguire codice o esempi da un ambiente di sviluppo locale, puoi eseguire l'autenticazione Compute Engine come segue.

    Select the tab for how you plan to use the samples on this page:

    Console

    When you use the Google Cloud console to access Google Cloud services and APIs, you don't need to set up authentication.

    gcloud

    1. Installa Google Cloud CLI, quindi initialize eseguendo questo comando:

      gcloud init
    2. Set a default region and zone.
    3. REST

      Per utilizzare gli esempi di API REST in questa pagina in un ambiente di sviluppo locale, utilizzi le credenziali che fornisci a gcloud CLI.

        Installa Google Cloud CLI, quindi initialize eseguendo questo comando:

        gcloud init

      Per ulteriori informazioni, vedi Esegui l'autenticazione per l'utilizzo di REST nella documentazione sull'autenticazione di Google Cloud.

Autorizzazioni richieste per questa attività

Per eseguire questa attività, devi disporre delle seguenti autorizzazioni:

  • compute.instances.get nell'istanza

Visualizzazione degli indirizzi IP

Puoi visualizzare gli indirizzi IP interni ed esterni dell'istanza tramite la console Google Cloud, Google Cloud CLI, oppure REST.

Console

Nella console Google Cloud, vai alla pagina Istanze VM. Se la VM ha un indirizzo IP esterno, viene visualizzato nella sezione IP esterno colonna. Se una VM non ha un indirizzo IP esterno, puoi assegnane uno.

Vai a Istanze VM

Pagina delle istanze VM che mostra gli IP interni ed esterni.

gcloud

Per visualizzare gli indirizzi IP interni ed esterni dell'istanza usando gcloud compute, usa instances list sottocomando.

gcloud compute instances list

L'output dovrebbe essere simile al seguente:

NAME              ZONE            MACHINE_TYPE     PREEMPTIBLE  INTERNAL_IP  EXTERNAL_IP    STATUS
hulk              us-central1-c   m1-ultramem-160  true         192.0.2.1                   RUNNING
my-instance       us-central1-c   e2-standard-2                 192.51.100.1  203.224.0.113 RUNNING

Per visualizzare l'indirizzo IP interno o esterno di un'istanza specifica utilizzando gcloud compute, usa instances describe con un flag --format per filtrare l'output. Ad esempio:

  • Per visualizzare l'IP interno per un'istanza specifica, esegui questo comando: :

    gcloud compute instances describe instance-name \
      --format='get(networkInterfaces[0].networkIP)'
    
    192.51.100.1
    
  • Per visualizzare l'IP esterno per un'istanza specifica, esegui questo comando :

    gcloud compute instances describe instance-name \
      --format='get(networkInterfaces[0].accessConfigs[0].natIP)'
    
    203.224.0.113
    

Sostituisci instance-name con il nome dell'istanza di cui vuoi visualizzare l'IP interno o esterno.

REST

Invia una richiesta GET a instances.get.

 GET https://compute.googleapis.com/compute/v1/projects/project-id/zones/zone/instances/instance-name
 

Sostituisci quanto segue:

  • project-id: l'ID progetto per questa query.
  • zone: la zona per l'istanza che vuoi query.
  • instance-name: il nome della risorsa istanza da restituire.

Il corpo della risposta è simile al seguente snippet:

{
  ...
  "networkInterfaces": [
    {
      ...
      "networkIP": "192.51.100.1",
      ...
      "accessConfigs": [
        {
          ...
          "name": "external-nat",
          "natIP": "203.224.0.113",
          ...
        }
      ],
      ...
    }
  ],
  ...
}

I seguenti campi contengono le informazioni richieste:

  • networkIP è l'indirizzo IP interno assegnato.
  • natIP è l'indirizzo IP esterno assegnato.

Python

from enum import Enum
from typing import List

from google.cloud import compute_v1


def get_instance(project_id: str, zone: str, instance_name: str) -> compute_v1.Instance:
    """
    Get information about a VM instance in the given zone in the specified project.

    Args:
        project_id: project ID or project number of the Cloud project you want to use.
        zone: name of the zone you want to use. For example: “us-west3-b”
        instance_name: name of the VM instance you want to query.
    Returns:
        An Instance object.
    """
    instance_client = compute_v1.InstancesClient()
    instance = instance_client.get(
        project=project_id, zone=zone, instance=instance_name
    )

    return instance


class IPType(Enum):
    INTERNAL = "internal"
    EXTERNAL = "external"
    IP_V6 = "ipv6"


def get_instance_ip_address(
    instance: compute_v1.Instance, ip_type: IPType
) -> List[str]:
    """
    Retrieves the specified type of IP address (ipv6, internal or external) of a specified Compute Engine instance.

    Args:
        instance (compute_v1.Instance): instance to get
        ip_type (IPType): The type of IP address to retrieve (ipv6, internal or external).

    Returns:
        List[str]: Requested type IP addresses of the instance.
    """
    ips = []
    if not instance.network_interfaces:
        return ips
    for interface in instance.network_interfaces:
        if ip_type == IPType.EXTERNAL:
            for config in interface.access_configs:
                if config.type_ == "ONE_TO_ONE_NAT":
                    ips.append(config.nat_i_p)
        elif ip_type == IPType.IP_V6:
            for ipv6_config in getattr(interface, "ipv6_access_configs", []):
                if ipv6_config.type_ == "DIRECT_IPV6":
                    ips.append(ipv6_config.external_ipv6)

        elif ip_type == IPType.INTERNAL:
            # Internal IP is directly available in the network interface
            ips.append(interface.network_i_p)
    return ips

Java


import com.google.cloud.compute.v1.AccessConfig;
import com.google.cloud.compute.v1.AccessConfig.Type;
import com.google.cloud.compute.v1.GetInstanceRequest;
import com.google.cloud.compute.v1.Instance;
import com.google.cloud.compute.v1.InstancesClient;
import com.google.cloud.compute.v1.NetworkInterface;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class GetVmAddress {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Google Cloud project you want to use.
    String projectId = "your-project-id";
    // Instance ID of the Google Cloud project you want to use.
    String instanceId = "your-instance-id";
    // IPType you want to search.
    IpType ipType = IpType.INTERNAL;

    getVmAddress(projectId, instanceId, ipType);
  }

  // Retrieves the specified type of IP address
  // (ipv6, internal or external) of a specified Compute Engine instance.
  public static List<String> getVmAddress(String projectId, String instanceId, IpType ipType)
          throws IOException {
    List<String> result = new ArrayList<>();
    Instance instance = getInstance(projectId, instanceId);

    for (NetworkInterface networkInterface : instance.getNetworkInterfacesList()) {
      if (ipType == IpType.EXTERNAL) {
        for (AccessConfig accessConfig : networkInterface.getAccessConfigsList()) {
          if (accessConfig.getType().equals(Type.ONE_TO_ONE_NAT.name())) {
            result.add(accessConfig.getNatIP());
          }
        }
      } else if (ipType == IpType.IP_V6) {
        for (AccessConfig accessConfig : networkInterface.getAccessConfigsList()) {
          if (accessConfig.hasExternalIpv6()
                  && accessConfig.getType().equals(Type.DIRECT_IPV6.name())) {
            result.add(accessConfig.getExternalIpv6());
          }
        }
      } else if (ipType == IpType.INTERNAL) {
        result.add(networkInterface.getNetworkIP());
      }
    }

    return result;
  }

  private static Instance getInstance(String projectId, String instanceId) throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (InstancesClient instancesClient = InstancesClient.create()) {
      GetInstanceRequest request = GetInstanceRequest.newBuilder()
              .setInstance(instanceId)
              .setProject(projectId)
              .setZone("us-central1-b")
              .build();
      return instancesClient.get(request);
    }
  }

  public enum IpType {
    INTERNAL("internal"),
    EXTERNAL("external"),
    IP_V6("ipv6");

    private final String type;

    IpType(String type) {
      this.type = type;
    }

    public String getType() {
      return type;
    }
  }
}