v9.1.1
Menu

Usable Hosts in a Subnet

easyPRONetworking & AddressingSystems & InfrastructureML Systems & Infrastructure 1

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

Input
print(usable_hosts(24))
Output
254
Reasoning
  • The input prefix length is p=24p = 24. Since 24<3124 < 31, the special cases for point-to-point links (/31/31) and host routes (/32/32) do not apply.
  • Calculate the total number of IP addresses in the subnet using the formula 2(32−p)2^{(32 - p)}: 2(32−24)=28=2562^{(32 - 24)} = 2^8 = 256.
  • Subtract the two reserved addresses (one for the network identifier and one for the broadcast address) from the total: 256−2=254256 - 2 = 254.
  • The final output is 254

Constraints

  • /31 -> 2, /32 -> 1.
  • Otherwise 2**(32-prefix) - 2.
  • Return an int.

More from ML Systems & Infrastructure 1

PRO

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.

solution.py

Test results

Sign in to run your code against the test cases.