Usable Hosts in a Subnet
Problem Statement
Given an IPv4 subnet prefix length, compute the number of usable host addresses.
Background
A /p subnet has 2(32-p)** total addresses. For p <= 30, two are reserved (network + broadcast), so usable hosts = 2(32-p) - 2**. A /31 has 2 usable (point-to-point, RFC 3021) and a /32 has 1 (host route).
Your Task
def usable_hosts(prefix):
Return the number of usable host addresses (int).
Input Format
- prefix (int), 0 <= prefix <= 32.
Output Format
- A single int.
Sample
print(usable_hosts(24))
Output:
254
Example
print(usable_hosts(24))
254
- The input prefix length is . Since , the special cases for point-to-point links () and host routes () do not apply.
- Calculate the total number of IP addresses in the subnet using the formula : .
- Subtract the two reserved addresses (one for the network identifier and one for the broadcast address) from the total: .
- The final output is 254
Constraints
/31-> 2,/32-> 1.- Otherwise
2**(32-prefix) - 2. - Return an int.