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 p=24. Since 24<31, the special cases for point-to-point links (/31) and host routes (/32) do not apply.
- Calculate the total number of IP addresses in the subnet using the formula 2(32−p): 2(32−24)=28=256.
- Subtract the two reserved addresses (one for the network identifier and one for the broadcast address) from the total: 256−2=254.
- The final output is 254
Constraints:
/31-> 2,/32-> 1.- Otherwise
2**(32-prefix) - 2. - Return an int.
1. Background Knowledge
IPv4 addresses are 32-bit integers. A subnet prefix length p determines how many leading bits are fixed for the network portion, leaving 32−p bits for the host portion. The total number of addresses in a subnet is therefore 232−p.
In traditional subnetting, two addresses are reserved: the network address (all host bits zero) and the broadcast address (all host bits one). This leaves 232−p−2 usable host addresses for most prefix lengths. However, two special cases exist defined by RFCs:
- A /31 subnet (point-to-point link, RFC 3021) has exactly 2 usable addresses because there is no separate broadcast address on a point-to-point link.
- A /32 subnet (host route) represents a single specific host, so it has exactly 1 usable address.
Understanding these edge cases is critical because blindly applying the 232−p−2 formula would yield 0 for /31 and −1 for /32, which are incorrect.
2. Algorithm Approach
This is a conditional arithmetic problem. The core logic involves:
- Computing the total address count via bit shifting: 232−p.
- Applying the standard subtraction of 2 for normal subnets.
- Handling the two special cases (prefix == 31 and prefix == 32) with explicit conditional branches that override the standard formula.
The pattern is: compute the general case, then check for exceptions. This is a common structure in networking problems where RFC-defined edge cases deviate from the general rule.
3. Step-by-Step Strategy
Continue the full explanation
You're reading the free preview. Unlock the complete walkthrough, the code editor, test runner and reference solution with Premium.
Editor locked
The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.