インスタンスの IP アドレスの特定


インスタンスの外部および内部 IP アドレスを特定する方法を説明します。

始める前に

  • まだ設定していない場合は、認証を設定します。認証とは、Google Cloud サービスと API にアクセスするために ID を確認するプロセスです。ローカル開発環境からコードまたはサンプルを実行するには、次のように Compute Engine に対する認証を行います。

    このページのサンプルをどのように使うかに応じて、タブを選択してください。

    コンソール

    Google Cloud コンソールを使用して Google Cloud サービスと API にアクセスする場合、認証を設定する必要はありません。

    gcloud

    1. Install the Google Cloud CLI, then initialize it by running the following command:

      gcloud init
    2. デフォルトのリージョンとゾーンを設定します

    REST

    このページの REST API サンプルをローカル開発環境で使用するには、gcloud CLI に指定した認証情報を使用します。

      Install the Google Cloud CLI, then initialize it by running the following command:

      gcloud init

このタスクに必要な権限

このタスクを行うには、次の権限が必要です。

  • インスタンスに対する compute.instances.get

IP アドレスの表示

インスタンスの内部 IP アドレスと外部 IP アドレスを確認するには、Google Cloud コンソールGoogle Cloud CLI または REST を使用します。

コンソール

Google Cloud コンソールの [VM インスタンス] ページに移動します。VM インスタンスに外部 IP アドレスがある場合は、[外部 IP] 列にアドレスが表示されます。VM に外部 IP アドレスがない場合は、アドレスを割り振ることができます。

[VM インスタンス] に移動

内部 IP と外部 IP が表示されている VM インスタンスのページ。

gcloud

gcloud compute を使用してインスタンスの内部 IP アドレスと外部 IP アドレスを表示するには、instances list サブコマンドを使用します。

gcloud compute instances list

出力は次のようになります。

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

gcloud compute を使用して特定のインスタンスの内部 IP アドレスまたは外部 IP アドレスを表示するには、instances describe サブコマンドで --format フラグを使用して、出力をフィルタリングします。例:

  • 特定のインスタンスの内部 IP を表示するには、次のコマンドを実行します。

    gcloud compute instances describe instance-name \
      --format='get(networkInterfaces[0].networkIP)'
    
    192.51.100.1
    
  • 特定のインスタンスの外部 IP を表示するには、次のコマンドを実行します。

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

instance-name は、内部 IP または外部 IP を表示するインスタンスの名前で置き換えます。

REST

instances.get メソッドに GET リクエストを送信します。

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

次のように置き換えます。

  • project-id: このクエリのプロジェクト ID。
  • zone: クエリを実行するインスタンスのゾーン。
  • instance-name: 返されるインスタンス リソースの名前。

レスポンスの本文は、次のスニペットのようになります。

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

必要な情報は次のフィールドに含まれています。

  • networkIP は、割り当てられた内部 IP アドレスです。
  • natIP は、割り当てられた外部 IP アドレスです。

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;
    }
  }
}