인스턴스 IP 주소 찾기


인스턴스의 외부 및 내부 IP 주소를 찾는 방법을 알아보세요.

시작하기 전에

  • 아직 인증을 설정하지 않았다면 설정합니다. 인증은 Google Cloud 서비스 및 API에 액세스하기 위해 ID를 확인하는 프로세스입니다. 로컬 개발 환경에서 코드 또는 샘플을 실행하려면 다음과 같이 Compute Engine에 인증하면 됩니다.

    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. Google Cloud CLI를 설치한 후 다음 명령어를 실행하여 초기화합니다.

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

      로컬 개발 환경에서 이 페이지의 REST API 샘플을 사용하려면 gcloud CLI에 제공하는 사용자 인증 정보를 사용합니다.

        Google Cloud CLI를 설치한 후 다음 명령어를 실행하여 초기화합니다.

        gcloud init

      자세한 내용은 Google Cloud 인증 문서의 REST 사용 인증을 참조하세요.

이 태스크에 필요한 권한

이 작업을 수행하려면 다음과 같은 권한이 있어야 합니다.

  • 인스턴스에 대한 compute.instances.get 권한

IP 주소 보기

Google Cloud 콘솔, Google Cloud CLI 또는 REST를 통해 인스턴스의 내부 및 외부 IP 주소를 볼 수 있습니다.

콘솔

Google Cloud Console에서 VM 인스턴스 페이지로 이동합니다. VM 인스턴스에 외부 IP 주소가 있으면 이 주소가 외부 IP 열에 표시됩니다. VM에 외부 IP 주소가 없으면 외부 IP 주소를 할당할 수 있습니다.

VM 인스턴스로 이동

내부 및 외부 IP를 보여주는 VM 인스턴스 페이지

gcloud

gcloud compute를 사용하여 인스턴스의 내부 및 외부 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 주소를 보려면 --format 플래그가 지정된 instances describe 하위 명령어를 사용하여 출력을 필터링합니다. 예를 들면 다음과 같습니다.

  • 특정 인스턴스의 내부 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

자바


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