如何获取已分配弹性IP的EC2实例的列表

本文关键字:IP EC2 列表 实例 分配 何获取 获取 | 更新日期: 2023-09-27 17:57:57

如何使用C#获得已分配静态公共Elastic IP的EC2实例的列表?

如何获取已分配弹性IP的EC2实例的列表

基本上,您将获得实例和公共IP,然后比较实例是否包含任何公共IP地址。

以下是将为您执行此操作的代码:

                AmazonEC2 ec2 = AWSClientFactory.CreateAmazonEC2Client();
                //Create instance request
                DescribeInstancesRequest request = new DescribeInstancesRequest();
                DescribeInstancesResponse response = ec2.DescribeInstances(request);
                //Create ip address request enumeration
                DescribeAddressesRequest daRequest = new DescribeAddressesRequest();
                DescribeAddressesResponse daResponse = ec2.DescribeAddresses(daRequest);
                var publicIps = from ips in daResponse.DescribeAddressesResult.Address select ips.PublicIp;
                //List of the instances which has public IP
                List<RunningInstance> publicIpInstances = new List<RunningInstance>();
                //Iterate over instances and check if they have public IP
                foreach (Reservation ri in response.DescribeInstancesResult.Reservation)                    
                    publicIpInstances.AddRange(ri.RunningInstance.Where(inst => publicIps.Contains(inst.IpAddress)));