DEV Community


Posted on

Python script to list unused IP addresses in AWS VPC Subnet

I wrote a Python script to list unused IP addresses (IPv4) in a subnet.

I have used Henry's post as a reference, thanks.


  1. Get the CIDR of specified subnet by DescribeSubnets
  2. Get the used private IP addresses in specified subnet by DescribeNetworkInterfaces = Used IP addresses
  3. Calculate the Unused IP addresses = "CIDR IP addresses" - "Used IP addresses" - "Reserved IP Addresses"


  • I used ipaddress module to calculate IP addresses within the CIDR.
  • I used "PrivateIpAddresses array" instead of "PrivateIpAddress" to extract both primary and secondary addresses from the NetworkInterface response.
  • Reserved IP addresses are described in official documentation

For example, if you create a VPC with CIDR block, it supports 256 IP addresses. You can break this CIDR block into two subnets, each supporting 128 IP addresses. One subnet uses CIDR block (for addresses - and the other uses CIDR block (for addresses -

Python script


  • >Python3.8
  • boto3
  • AWS Permissions
    • ec2:DescribeSubnets
    • ec2:DescribeNetworkInterfaces


export AWS_DEFAULT_REGION={region name}
export AWS_DEFAULT_PROFILE={aws profile name}
python {subnet-id}
Enter fullscreen mode Exit fullscreen mode
export AWS_DEFAULT_REGION=ap-northeast-1
export AWS_DEFAULT_PROFILE=my_aws_account
python subnet-000000000000
Enter fullscreen mode Exit fullscreen mode


subnet_id='subnet-000000000000' mode='normal'
cidr_ips=['', '', '', '', '', ...]
reserved_ips=['', '', '', '', '']
unused_ips=['', '', '', ...]
cidr= cidr_ips=256 reserved=5 used=1 unused=250
Enter fullscreen mode Exit fullscreen mode

Top comments (0)