Is there a function to get the first and last IP of a CIDR block?

Given 10.100.0.0/16 I want to get the IP range.

startIP 10.100.0.0

endIP 10.100.255.255

Is there a function to get the first and last IP of a CIDR block?

Given 10.100.0.0/16 I want to get the IP range.

startIP 10.100.0.0

endIP 10.100.255.255

cidrhost function can be of help. cidrhost - Functions - Configuration Language - Terraform by HashiCorp

Hi @deasunk,

As @deshaks noted, the `cidrhost`

function is the main way to go from subnet addresses in CIDR notation to specific host addresses within that subnet.

Getting the starting IP address is easier because we know its number will always be zero:

```
> cidrhost("10.100.0.0/16", 0)
"10.100.0.0"
```

Getting the ending IP address is harder because we need to calculate the largest number we can represent in the remaining bits. Terraform doesn’t have a dedicated function for that but it has some building blocks you can use to get there:

```
# Find the prefix length part of the CIDR notation
> parseint(regex("/(\\d+)$", "10.100.0.0/16")[0], 10)
16
# Subtract from the total number of bits in the address
# to get the number of remaining bits.
# I'm assuming IPv4 here, which has a total of 32 bits.
> 32 - 16
16
# Find the 16th power of 2, which is the number of
# host addresses we can assign with 16 bits of
# host address space.
> pow(2, 16)
65536
# The final host address is therefore one less than
# that result, because the first host address is
# numbered zero.
> cidrhost("10.100.0.0/16", 65536-1)
"10.100.255.255"
```

(The examples above are `terraform console`

output where I was working through this. To use this in your real configuration you can write these expressions out as local values, and possibly combine some of the steps together into a more complex expression since you likely won’t need the intermediate results anywhere else in your module.)

1 Like

Hi @deasunk and @apparentlymart,

no need for all that fancy regex and converting, `cidrhost`

has it built-in:

```
> cidrhost("10.100.0.0/16", 0)
"10.100.0.0"
> cidrhost("10.100.0.0/16", -1)
"10.100.255.255"
```

And so on and so forth, e.g. for the last host IP in a subnet:

```
> cidrhost("10.100.0.0/16", -2)
"10.100.255.254"
```