Drill

ProblemsGo › network

How many hosts fit in a CIDR block

easynetworkMathBit manipulationGo

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.

cidrHosts(prefixBits: int) → int

Go needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

func cidrHosts(prefixBits int) int {
	
}

Worked examples

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

Hint

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

Reference solution in Go
func cidrHosts(prefixBits int) int {
	if prefixBits < 1 || prefixBits >= 31 {
		return 0
	}
	exp := 32 - prefixBits
	hosts := 1
	for i := 0; i < exp; i++ {
		hosts = hosts * 2
	}
	return hosts - 2
}

The same problem in another language

More network problems in Go