Drill

ProblemsPython › network

How many hosts fit in a CIDR block

easynetworkPython

An IPv4 CIDR prefix carves out a block of addresses. Two are reserved — the network address and the broadcast — so the rest are usable hosts.

cidr_hosts(prefix_bits: int) → int

Solve it in the editor →

Where you start

def cidr_hosts(prefix_bits: int) -> int:
    

Worked examples

CallResult
cidr_hosts(24)254
cidr_hosts(8)16777214
cidr_hosts(16)65534
cidr_hosts(31)0

Hint

Start at 1 and double it (32 − prefixBits) times.

Reference solution in Python
def cidr_hosts(prefix_bits: int) -> int:
    if prefix_bits < 1 or prefix_bits >= 31:
        return 0
    exp = 32 - prefix_bits
    hosts = 1
    for _ in range(exp):
        hosts = hosts * 2
    return hosts - 2

The same problem in another language

More network problems in Python