

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 在 Amazon EC2 中使用彈性 IP 地址
<a name="examples-ec2-elastic-ip"></a>

## 先決條件
<a name="codeExamplePrereq"></a>

開始之前，建議您先閱讀[開始使用 適用於 C\$1\$1 的 AWS SDK](getting-started.md)。

下載範例程式碼並建置解決方案，如中所述[程式碼範例入門](getting-started-code-examples.md)。

若要執行範例，您的程式碼用來提出請求的使用者描述檔必須具有 AWS （針對 服務和 動作） 的適當許可。如需詳細資訊，請參閱[提供 AWS 登入](credentials.md)資料。

## 配置彈性 IP 地址
<a name="allocate-an-elastic-ip-address"></a>

若要使用彈性 IP 位址，您可以先將一個地址配置給帳戶，再將其與您的執行個體或網路介面建立關聯。

若要配置彈性 IP 地址，請使用包含 網路類型的 [AllocateAddressRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_allocate_address_request.html) 物件 （傳統 EC2 或 VPC) 呼叫 EC2Client 的 `AllocateAddress`函數。

**警告**  
我們將於 2022 年 8 月 15 日淘汰 EC2-Classic。建議您從 EC2-Classic 遷移至 VPC。如需詳細資訊，請參閱《Amazon ** EC2 Linux 執行個體使用者指南》或《Amazon EC2 Windows 執行個體使用者指南》中的從 EC2-Classic 遷移至 VPC**。 [Amazon EC2 ](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-migrate.html) [Amazon EC2 ](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/vpc-migrate.html) 也請參閱部落格文章 [EC2-Classic 網路正在淘汰 - 本文介紹如何準備](https://aws.amazon.com/blogs/aws/ec2-classic-is-retiring-heres-how-to-prepare/)。

回應物件中的 [AllocateAddressResponse](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_allocate_address_response.html) 類別包含一個配置 ID，您可以將 [AssociateAddressRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_associate_address_request.html) 中的配置 ID 和執行個體 ID 傳遞至 EC2Client 的 `AssociateAddress`函數，藉此將地址與執行個體建立關聯。

 **包括** 

```
#include <aws/ec2/EC2Client.h>
#include <aws/ec2/model/AllocateAddressRequest.h>
#include <aws/ec2/model/AssociateAddressRequest.h>
#include <iostream>
```

 **Code** 

```
    Aws::EC2::EC2Client ec2Client(clientConfiguration);

    Aws::EC2::Model::AllocateAddressRequest request;
    request.SetDomain(Aws::EC2::Model::DomainType::vpc);

    const Aws::EC2::Model::AllocateAddressOutcome outcome =
            ec2Client.AllocateAddress(request);
    if (!outcome.IsSuccess()) {
        std::cerr << "Failed to allocate Elastic IP address:" <<
                  outcome.GetError().GetMessage() << std::endl;
        return false;
    }
    const Aws::EC2::Model::AllocateAddressResponse &response = outcome.GetResult();
    allocationID = response.GetAllocationId();
    publicIPAddress = response.GetPublicIp();


    Aws::EC2::Model::AssociateAddressRequest associate_request;
    associate_request.SetInstanceId(instanceId);
    associate_request.SetAllocationId(allocationID);

    const Aws::EC2::Model::AssociateAddressOutcome associate_outcome =
            ec2Client.AssociateAddress(associate_request);
    if (!associate_outcome.IsSuccess()) {
        std::cerr << "Failed to associate Elastic IP address " << allocationID
                  << " with instance " << instanceId << ":" <<
                  associate_outcome.GetError().GetMessage() << std::endl;
        return false;
    }

    std::cout << "Successfully associated Elastic IP address " << allocationID
              << " with instance " << instanceId << std::endl;
```

請參閱[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2/allocate_address.cpp)。

## 說明彈性 IP 地址
<a name="describe-elastic-ip-addresses"></a>

若要列出指派給您帳戶的彈性 IP 地址，請呼叫 EC2Client 的 `DescribeAddresses`函數。它會傳回結果物件，其中包含 [DescribeAddressesResponse](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_describe_addresses_response.html)，可用來取得代表您帳戶中彈性 IP 地址的[位址](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_address.html)物件清單。

 **包括** 

```
#include <aws/ec2/EC2Client.h>
#include <aws/ec2/model/DescribeAddressesRequest.h>
#include <aws/ec2/model/DescribeAddressesResponse.h>
#include <iomanip>
#include <iostream>
```

 **Code** 

```
    Aws::EC2::EC2Client ec2Client(clientConfiguration);
    Aws::EC2::Model::DescribeAddressesRequest request;
    Aws::EC2::Model::DescribeAddressesOutcome outcome = ec2Client.DescribeAddresses(request);
    if (outcome.IsSuccess()) {
        std::cout << std::left << std::setw(20) << "InstanceId" <<
                  std::setw(15) << "Public IP" << std::setw(10) << "Domain" <<
                  std::setw(30) << "Allocation ID" << std::setw(25) <<
                  "NIC ID" << std::endl;

        const Aws::Vector<Aws::EC2::Model::Address> &addresses = outcome.GetResult().GetAddresses();
        for (const auto &address: addresses) {
            Aws::String domainString =
                    Aws::EC2::Model::DomainTypeMapper::GetNameForDomainType(
                            address.GetDomain());

            std::cout << std::left << std::setw(20) <<
                      address.GetInstanceId() << std::setw(15) <<
                      address.GetPublicIp() << std::setw(10) << domainString <<
                      std::setw(30) << address.GetAllocationId() << std::setw(25)
                      << address.GetNetworkInterfaceId() << std::endl;
        }
    } else {
        std::cerr << "Failed to describe Elastic IP addresses:" <<
                  outcome.GetError().GetMessage() << std::endl;
    }
```

請參閱[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2/describe_addresses.cpp)。

## 釋出彈性 IP 地址
<a name="release-an-elastic-ip-address"></a>

若要釋出彈性 IP 地址，請呼叫 EC2Client 的 `ReleaseAddress`函數，並向其傳遞 [ReleaseAddressRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_release_address_request.html)，其中包含您要釋出之彈性 IP 地址的配置 ID。

 **包括** 

```
#include <aws/ec2/EC2Client.h>
#include <aws/ec2/model/ReleaseAddressRequest.h>
#include <iostream>
```

 **Code** 

```
    Aws::EC2::EC2Client ec2(clientConfiguration);

    Aws::EC2::Model::ReleaseAddressRequest request;
    request.SetAllocationId(allocationID);

    Aws::EC2::Model::ReleaseAddressOutcome outcome = ec2.ReleaseAddress(request);
    if (!outcome.IsSuccess()) {
        std::cerr << "Failed to release Elastic IP address " <<
                  allocationID << ":" << outcome.GetError().GetMessage() <<
                  std::endl;
    } else {
        std::cout << "Successfully released Elastic IP address " <<
                  allocationID << std::endl;
    }
```

釋出彈性 IP 地址後，該地址會釋出到 AWS IP 地址集區，您之後可能無法使用。請務必更新您的 DNS 記錄以及與該地址通訊的任何伺服器或裝置。如果您嘗試釋出已發行的彈性 IP 地址，如果地址已配置給另一個 AWS 帳戶，則會收到 *AuthFailure* 錯誤。

如果您使用的是*預設 VPC*，則釋放彈性 IP 地址會自動將其與與其相關聯的任何執行個體取消關聯。若要取消彈性 IP 地址的關聯而不釋出，請使用 EC2Client 的 `DisassociateAddress`函數。

如果您是使用非預設 VPC，在嘗試釋出該彈性 IP 地址前，您*必須*先使用 `DisassociateAddress` 將其取消關聯。否則，Amazon EC2 會傳回錯誤 (*InvalidIPAddress.InUse*)。

請參閱[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2/release_address.cpp)。

## 詳細資訊
<a name="more-information"></a>
+  《Amazon EC2 使用者指南》中的[彈性 IP 地址](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html) 
+  Amazon EC2 API 參考中的 [AllocateAddress](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_AllocateAddress.html) 
+  Amazon EC2 API 參考中的 [DescribeAddresses](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeAddresses.html) 
+  Amazon EC2 API 參考中的 [ReleaseAddress](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ReleaseAddress.html) 