查看執行個體的網路設定


請按照本頁說明操作,查看運算執行個體的網路介面、網路、子網路和 IP 位址。

事前準備

  • 如果尚未設定,請先設定驗證機制。驗證是指驗證身分,以便存取 Google Cloud 服務和 API 的程序。如要在本機開發環境中執行程式碼或範例,您可以選取下列任一選項,向 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. After installing the Google Cloud CLI, initialize it by running the following command:

      gcloud init

      If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

    2. Set a default region and zone.

    REST

    To use the REST API samples on this page in a local development environment, you use the credentials you provide to the gcloud CLI.

      After installing the Google Cloud CLI, initialize it by running the following command:

      gcloud init

      If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

    For more information, see Authenticate for using REST in the Google Cloud authentication documentation.

必要的角色

如要取得查看執行個體網路設定所需的權限,請要求管理員為您授予專案的 Compute 執行個體管理員 (v1) (roles/compute.instanceAdmin.v1) 或 Compute 網路管理員 (roles/compute.networkAdmin) IAM 角色。如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和機構的存取權」。

這個預先定義的角色具備查看執行個體網路設定所需的權限。如要查看確切的必要權限,請展開「必要權限」部分:

所需權限

您必須具備下列權限,才能查看執行個體的網路設定:

  • 查看執行個體的網路設定: compute.instances.get 在執行個體上
  • 查看執行個體的 IP 位址: compute.instances.list 在專案中

您或許還可透過自訂角色或其他預先定義的角色取得這些權限。

查看 IP 位址

您可以查看執行個體的內部和外部 IP 位址。IP 位址可以是 IPv4 或 IPv6 位址。

主控台

  1. 前往 Google Cloud 控制台的「VM instances」(VM 執行個體) 頁面

    前往 VM 執行個體

  2. 選用:使用 「Filter」方塊限制顯示的例項數量。

  3. 如果執行個體有外部 IP 位址,該位址會顯示在「外部 IP」欄下方。

    如果執行個體沒有外部 IP 位址,您可以指派一個

顯示內部和外部 IP 的 VM 執行個體頁面。

視資料欄顯示選項而定,您可能會看到比上一個圖片中更多的資料欄,也可能會看到更少的資料欄。

gcloud

您可以使用兩個指令查看執行個體的 IP 位址:

  • gcloud compute instances list 會顯示運算執行個體使用的所有 IP 位址,包括靜態或臨時 IP 位址。
  • gcloud compute addresses list 會顯示指派給運算執行個體的所有保留 IP 位址。

本任務將說明如何使用 gcloud compute instances 指令查看 IP 位址。

  1. 如要查看執行個體的內部和外部 IP 位址,請使用 gcloud compute instances list 指令

    gcloud compute instances list

    您可以附加 --filter 子句,限制指令傳回的例項數量,例如 --filter='zone:us-central1-c'

    輸出結果會與下列內容相似:

    NAME           ZONE            MACHINE_TYPE    PREEMPTIBLE  INTERNAL_IP                EXTERNAL_IP                     STATUS
    webapp1        us-central1-c   c3-highmem-88   true         192.0.2.11                                                 RUNNING
    my-instance    us-central1-c   n4-standard-2                192.0.2.126                203.0.113.6                     RUNNING
    my-dual-stack  us-central1-a   e2-micro                     192.0.2.54                 203.0.113.7                     RUNNING
                                                                                          2001:db8:2:2:2:2:2:2/96
    new-ipv6-only  us-central1-a   n4-standard-2                2001:db8:1:1:1:1:1:1/96                                    RUNNING
    
  2. 如要查看特定執行個體的內部或外部 IP 位址,請使用 gcloud compute instances describe 指令搭配 --format 旗標來篩選輸出內容。

    內部位址

    如要查看特定執行個體的內部 IP 位址,請使用下列任一指令:

    • IPv4 位址:

         gcloud compute instances describe INSTANCE_NAME \
             --zone=ZONE \
             --format='get(networkInterfaces[0].networkIP)'
        
      192.0.2.11
    • IPv6 位址:

         gcloud compute instances describe INSTANCE_NAME \
             --zone=ZONE \
             --format='get(networkInterfaces[0].ipv6Address)'
        
      2001:db8:2:2:2:2:2:2

    外部地址

    如要查看特定執行個體的外部 IP 位址,請使用下列任一指令:

    • IPv4 位址:

         gcloud compute instances describe INSTANCE_NAME \
             --zone=ZONE \
             --format='get(networkInterfaces[0].accessConfigs[0].natIP)'
        
      203.0.113.6
    • IPv6 位址:

         gcloud compute instances describe INSTANCE_NAME \
             --zone=ZONE \
             --format='get(networkInterfaces[0].ipv6AccessConfigs[0].externalIpv6)'
        
      2001:db8:3:3:3:3:3:3

    更改下列內容:

    • INSTANCE_NAME:您要查看內部或外部 IP 的執行個體名稱
    • ZONE:執行個體所在的可用區名稱。

    如果指令未傳回 IP 位址,表示執行個體未設定外部 IP 位址。

REST

instances.get 方法提出 GET 要求。只要在要求中附加 $fields 查詢參數,即可將輸出內容限制為只包含您感興趣的欄位。

 GET https://compute.googleapis.com/compute/v1/projects/PROJECT_NAME/zones/ZONE/instances/INSTANCE_NAME$fields=name,networkInterfaces.networkIP,networkInterfaces.accessConfigs.natIP,networkInterfaces.ipv6AccessConfigs.externalIpv6
 

更改下列內容:

  • PROJECT_NAME:包含執行個體的專案名稱。
  • ZONE:要查詢的執行個體區域。
  • INSTANCE_NAME:要傳回的執行個體資源名稱。

如果未設定任何 IP 位址,則該欄位不會出現在輸出內容中。如果是使用雙堆疊網路 (含外部 IPv6 位址) 的運算執行個體,回應主體會類似以下內容:

{
  "name": "my-dual-stack-vm",
  "networkInterfaces": [
    {
      "networkIP": "10.0.0.2",
      "accessConfigs": [
        {
          "natIP": "104.155.21.204"
        }
      ],
      "ipv6AccessConfigs": [
        {
          "externalIpv6": "2600:1900:4010:8b2:0:0:0:0"
        }
      ]
    }
  ]
}

下列欄位包含必要資訊:

  • networkIP:指派的內部 IPv4 位址。
  • natIP:指派的外部 IPv4 位址。
  • externalIpv6:指派的外部 IPv6 位址。

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

查看執行個體的網路介面

每個運算執行個體至少都有一個網路介面。您可以透過下列方式查看執行個體的網路介面設定屬性。

主控台

  1. 前往 Google Cloud 控制台的「VM instances」(VM 執行個體) 頁面

    前往 VM 執行個體

  2. 選用:使用 「Filter」方塊限制顯示的例項數量。

  3. 按一下要檢查的執行個體名稱。

  4. 在「網路」區段的「網路介面」下方,您可以查看為執行個體建立的網路介面 (NIC)、與每個 NIC 相關聯的網路和子網路,以及其指派的 IP 位址。

  5. 您可以按一下 NIC 名稱,開啟「網路介面詳細資料」頁面。您可以在這個頁面上查看 NIC 使用的防火牆和路徑,並為 NIC 執行連線測試。

gcloud

如要查看運算執行個體的網路介面 (NIC),請使用 gcloud compute instances describe 指令。您可以將 --format 選項附加至指令,限制傳回至特定欄位的資訊,並變更資訊的顯示方式,例如:

gcloud compute instances describe INSTANCE_NAME --zone=ZONE \
    --format="flattened(name,networkInterfaces[].name, networkInterfaces[].network.basename(), networkInterfaces[].stackType, networkInterfaces[].nicType)"

上述指令會傳回類似以下的輸出內容:

name:                           my-multinic-vm
networkInterfaces[0].name:      nic0
networkInterfaces[0].network:   default
networkInterfaces[0].nicType:   GVNIC
networkInterfaces[0].stackType: IPV4_ONLY
networkInterfaces[1].name:      nic1
networkInterfaces[1].network:   appnet-vpc-0
networkInterfaces[1].nicType:   GVNIC
networkInterfaces[1].stackType: IPV4_IPV6

REST

建構對 instances.get 方法GET 要求。只要在要求中附加 $fields 查詢參數,即可將輸出內容限制為僅包含 networkInterfaces 屬性。

GET https://compute.googleapis.com/compute/v1/projects/PROJECT_NAME/zones/ZONE/instances/INSTANCE_NAME?$fields=networkInterfaces

更改下列內容:

  • PROJECT_NAME:包含執行個體的專案名稱。
  • ZONE:要查詢的執行個體區域。
  • INSTANCE_NAME:要傳回的執行個體資源名稱。

回應主體應類似以下內容:

{
  "networkInterfaces": [
  {
    "kind": "compute#networkInterface",
    "network": "https://www.googleapis.com/compute/v1/projects/my-project/global/networks/network-name-1",
    "subnetwork": "https://www.googleapis.com/compute/v1/projects/my-project/regions/us-central1/subnetworks/subnet-name-1",
    "networkIP": "10.128.0.15",
    "name": "nic0",
    "accessConfigs": [
      {
        "kind": "compute#accessConfig",
        "type": "ONE_TO_ONE_NAT",
        "name": "External NAT",
        "networkTier": "PREMIUM"
      }
    ],
    "fingerprint": "mBy9xvkWA9M=",
    "stackType": "IPV4_ONLY",
    "nicType": "GVNIC"
  },
  {
    "kind": "compute#networkInterface",
    "network": "https://www.googleapis.com/compute/v1/projects/my-project/global/networks/network-name-2",
    "subnetwork": "https://www.googleapis.com/compute/v1/projects/my-project/regions/us-central1/subnetworks/subnet-name-2",
    "networkIP": "10.0.20.2",
    "name": "nic1",
    "accessConfigs": [
      {
        "kind": "compute#accessConfig",
        "type": "ONE_TO_ONE_NAT",
        "name": "External NAT",
        "networkTier": "PREMIUM"
      }
    ],
    "ipv6AccessConfigs": [
      {
        "kind": "compute#accessConfig",
        "type": "DIRECT_IPV6",
        "name": "external-ipv6",
        "externalIpv6": "2600:1900:4000:8447:0:0:0:0",
        "externalIpv6PrefixLength": 96,
        "publicPtrDomainName": "",
        "networkTier": "PREMIUM"
      }
    ],
    "fingerprint": "rx6hfNA94f4=",
    "stackType": "IPV4_IPV6",
    "ipv6AccessType": "EXTERNAL",
    "nicType": "GVNIC"
  }
  ]
}

查看網路中的所有運算執行個體

請使用下列其中一種方法,查看特定網路中的所有運算執行個體。

主控台

  1. 在 Google Cloud 控制台中,前往「虛擬私有雲網路」頁面。

    前往「VPC networks」(虛擬私有雲網路)

  2. 選用步驟:使用 「Filter」方塊,限制顯示的網路數量。

  3. 按一下要列出運算單元的網路名稱。

  4. 選取「Instances」分頁標籤,即可查看該網路中的執行個體。

gcloud

如要查看使用特定網路的運算子,請使用 gcloud compute instances list 指令

使用 --filter 標記,只列出使用特定網路的執行個體。您也可以使用 --format 標記限制及設定結果的格式,例如:

gcloud compute instances list \
    --filter 'networkInterfaces[].network:NETWORK_NAME' \
    --format="table(name:sort=1,machineType.basename(),zone.basename(),networkInterfaces[].subnetwork)"

輸出結果會與下列內容相似:

NAME: c2-tier1-multinic
MACHINE_TYPE: c2-standard-30
ZONE: us-central1-c
SUBNETWORK: ['https://www.googleapis.com/compute/v1/projects/my-project/regions/us-central1/subnetworks/default', 'https://www.googleapis.com/compute/v1/projects/my-project/regions/us-central1/subnetworks/webapps-external-subnet']
NAME: c3-with-lssd MACHINE_TYPE: c3-standard-4-lssd ZONE: us-central1-a SUBNETWORK: ['https://www.googleapis.com/compute/v1/projects/my-project/regions/us-central1/subnetworks/default']
NAME: example-instance3 MACHINE_TYPE: n2-custom-2-163840-ext ZONE: us-central1-b SUBNETWORK: ['https://www.googleapis.com/compute/v1/projects/my-project/regions/us-central1/subnetworks/default']
NAME: n4-test-windows MACHINE_TYPE: n4-standard-2 ZONE: us-central1-c SUBNETWORK: ['https://www.googleapis.com/compute/v1/projects/my-project/regions/us-central1/subnetworks/default']

判斷是否已啟用 Tier_1 網路

請使用下列其中一種方法,判斷是否已為執行個體啟用各個 VM 的 Tier_1 網路效能。

主控台

  1. 前往 Google Cloud 控制台的「VM instances」(VM 執行個體) 頁面

    前往 VM 執行個體

  2. 選用:使用 「Filter」方塊限制顯示的例項數量。

  3. 按一下要檢查的執行個體名稱。

  4. 在「Networking」部分,檢查「Total egress bandwidth tier」的值:

    • TIER_1:已啟用 Tier_1 網路。
    • -:未啟用 Tier_1 網路。

gcloud

如要查看執行個體的 networkPerformanceConfig 設定,請使用 gcloud compute instances describe 指令。您可以將 --format 選項附加至指令,限制傳回至特定欄位的資訊,並變更資訊的顯示方式,例如:

gcloud compute instances describe INSTANCE_NAME \
    --zone=ZONE \
    --format="text(name, networkPerformanceConfig)"

如果未為執行個體設定 Tier_1 網路,輸出內容就不會包含 networkPerformanceConfig 欄位。如果已為執行個體啟用 Tier_1 網路,輸出內容會類似以下內容:

name:                                              c2-tier1-multinic
networkPerformanceConfig.totalEgressBandwidthTier: TIER_1

REST

建構對 instances.get 方法GET 要求。只要在要求中附加 $fields 查詢參數,即可將輸出內容限制為僅限 namenetworkPerformanceConfignicType 欄位。

GET https://compute.googleapis.com/compute/v1/projects/PROJECT_NAME/zones/ZONE/instances/INSTANCE_NAME?$fields=name,networkPerformanceConfig,networkInterfaces.nicType

更改下列內容:

  • PROJECT_NAME:包含執行個體的專案名稱。
  • ZONE:要查詢的執行個體區域。
  • INSTANCE_NAME:要傳回的執行個體資源名稱。

如果未為執行個體設定 Tier_1 網路,輸出內容就不會包含 networkPerformanceConfig 欄位。如果已為執行個體啟用 Tier_1 網路,輸出內容會類似以下內容:

{
  "name": "c2-tier1-multinic",
  "networkInterfaces": [
    {
      "nicType": "GVNIC"
    },
    {
      "nicType": "GVNIC"
    }
  ],
  "networkPerformanceConfig": {
    "totalEgressBandwidthTier": "TIER_1"
  }
}