查找实例的 IP 地址


了解如何查找实例的外部和内部 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. 安装 Google Cloud CLI,然后通过运行以下命令初始化 Google Cloud CLI:

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

      如需在本地开发环境中使用本页面上的 REST API 示例,请使用您提供给 gcloud CLI 的凭据。

        安装 Google Cloud CLI,然后通过运行以下命令初始化 Google Cloud CLI:

        gcloud init

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

执行此任务所需的权限

您必须拥有以下权限才能执行此任务:

  • 针对实例的 compute.instances.get 权限

查看 IP 地址

您可以通过 Google Cloud 控制台Google Cloud CLI REST 查看实例的内部和外部 IP 地址。

控制台

在 Google Cloud 控制台中,转到虚拟机实例页面。如果虚拟机实例具有外部 IP 地址,则该地址会显示在外部 IP 列下方。如果虚拟机没有外部 IP 地址,您可以为其分配一个

转到“虚拟机实例”

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

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 的实例的名称。

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 地址。