查看实例的网络配置


请按照本页面上的说明查看计算实例的网络接口、网络、子网和 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.
    3. REST

      如需在本地开发环境中使用本页面上的 REST API 示例,请使用您提供给 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.

      如需了解详情,请参阅 Google Cloud 身份验证文档中的使用 REST 时进行身份验证

所需的角色

如需获得查看实例的网络配置所需的权限,请让管理员为您授予项目的 Compute Instance Admin (v1) (roles/compute.instanceAdmin.v1) 或 Compute Network Admin (roles/compute.networkAdmin) IAM 角色。如需详细了解如何授予角色,请参阅管理对项目、文件夹和组织的访问权限

此预定义角色包含查看实例的网络配置所需的权限。如需查看所需的确切权限,请展开所需权限部分:

所需权限

您需要具备以下权限才能查看实例的网络配置:

  • 查看实例的网络配置:针对实例的 compute.instances.get 权限
  • 查看实例的 IP 地址:针对项目的 compute.instances.list 权限

您也可以使用自定义角色或其他预定义角色来获取这些权限。

查看 IP 地址

您可以查看实例的内部和外部 IP 地址。IP 地址可以是 IPv4 或 IPv6 地址。

控制台

  1. 在 Google Cloud 控制台中,前往虚拟机实例页面。

    进入“虚拟机实例”

  2. 可选:使用 过滤条件框限制显示的实例数量。

  3. 如果实例具有外部 IP 地址,则该地址会显示在外部 IP 列下方。

    如果外部 IP 列为空,则表示实例没有外部 IP 地址。如果实例没有外部 IP 地址,您可以分配一个

显示内部和外部 IP 的虚拟机实例页面。

根据列显示选项的不同,您看到的列可能会比上图中显示的列更多或更少。

gcloud

您可以使用以下两个命令查看实例的 IP 地址:

  • gcloud compute instances list 会显示计算实例使用的所有 IP 地址,无论是静态 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
    

    如果外部 IP 地址字段为空,则表示该实例没有定义该类型的 IP 地址;您可以分配一个

  2. 如需查看特定实例的内部或外部 IP 地址,请使用带 --format 标志的 gcloud compute instances describe 命令来过滤输出。

    内部地址

    如需查看特定实例的内部 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 控制台中,前往虚拟机实例页面。

    进入“虚拟机实例”

  2. 可选:使用 过滤条件框限制显示的实例数量。

  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)"

替换以下内容:

  • INSTANCE_NAME:要查看的实例的名称
  • ZONE:您要查看的实例的可用区。

输出类似于以下内容:

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"
  }
  ]
}

查看实例的 Dynamic Network Interface 配置

如果您为实例配置了动态网卡,可以使用以下方法之一查看动态网卡信息。

gcloud

如需查看计算实例的网络接口 (NIC),请使用 gcloud beta compute instances describe 命令。您可以向该命令附加 --format 选项,以限制返回到特定字段的信息并更改其显示方式,例如:

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

输出类似于以下内容:

name:                           test-instance
networkInterfaces[0].name:      nic0
networkInterfaces[0].network:   default
networkInterfaces[0].nicType:   GVNIC
networkInterfaces[0].stackType: IPV4_ONLY
networkInterfaces[1].name:      nic1
networkInterfaces[1].network:   prod-ipv6
networkInterfaces[1].nicType:   GVNIC
networkInterfaces[1].stackType: IPV4_IPV6
networkInterfaces[1].name:      nic1.2
networkInterfaces[1].network:   alt-ipv6-net
networkInterfaces[1].nicType:   GVNIC
networkInterfaces[1].stackType: IPV4_IPV6
networkInterfaces[1].parentNicName: nic1

REST

构建对 instances.get 方法的 GET 请求。通过向请求附加 $fields 查询参数,您可以将输出限制为仅包含 networkInterfaces 属性。

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_ID:包含实例的项目的 ID
  • ZONE:实例的可用区
  • INSTANCE_NAME:实例的名称。

HTTP 方法和网址:

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

如需发送您的请求,请展开以下选项之一:

您应该收到类似以下内容的 JSON 响应:

{
  "networkInterfaces": [
  {
    "kind": "compute#networkInterface",
    "network": "https://www.googleapis.com/compute/beta/projects/my-project/global/networks/network-name-1",
    "subnetwork": "https://www.googleapis.com/compute/beta/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/beta/projects/my-project/global/networks/network-name-2",
    "subnetwork": "https://www.googleapis.com/compute/beta/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",
    "parentNicName": "nic1"
  },
  {
    "kind": "compute#networkInterface",
    "network": "https://www.googleapis.com/compute/beta/projects/my-project/global/networks/network-name-3",
    "subnetwork": "https://www.googleapis.com/compute/beta/projects/my-project/regions/us-central1/subnetworks/subnet-name-3",
    "networkIP": "10.0.26.2",
    "name": "nic1.1",
    "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:8450:0:0:0:0",
        "externalIpv6PrefixLength": 96,
        "publicPtrDomainName": "",
        "networkTier": "PREMIUM"
      }
    ],
    "fingerprint": "rx6hfNA94f4=",
    "stackType": "IPV4_IPV6",
    "ipv6AccessType": "EXTERNAL",
    "nicType": "GVNIC",
    "parentNicName": "nic1"
  }
  ]
}

查看网络中的所有计算实例

使用以下方法之一可查看特定网络中的所有计算实例。

控制台

  1. 在 Google Cloud 控制台中,前往 VPC 网络页面。

    进入 VPC 网络页面

  2. 可选:使用 过滤条件框限制显示的网络数量。

  3. 点击要列出其计算实例的网络的名称。

  4. 选择实例标签页,以查看该网络中的实例。

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 网络

使用以下任一方法可确定是否为实例启用了每个虚拟机的 Tier_1 网络性能。

控制台

  1. 在 Google Cloud 控制台中,前往虚拟机实例页面。

    进入“虚拟机实例”

  2. 可选:使用 过滤条件框限制显示的实例数量。

  3. 点击要检查的实例的名称。

  4. 网络部分中,查看总出站流量带宽层级的值:

    • 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"
  }
}