Bitwise AND & usable host counts
Network, broadcast, and hosts
Lesson 4 of 20 · 11 min · Module 1: Addresses are numbers
Two addresses are on the same network when their network bits match. A bitwise AND with the mask removes the host bits and reveals the network address.
Start this lesson →Free. No installation: you write and run the code in your browser, and it is checked automatically.
By the end, you’ll be able to…
- Find the network address with AND
- Find the broadcast address with OR and NOT
- Count usable host addresses
The idea
Convert the address to one integer: (a << 24) | (b << 16) | (c << 8) | d. The network is ip & mask. The broadcast address sets every host bit to 1: network | (~mask & 0xFFFFFFFF). For prefixes up to /30, usable hosts are 2 ** (32 - prefix) - 2: the network and broadcast addresses are reserved.
ip = (192 << 24) | (168 << 16) | (1 << 8) | 77
mask = (0xFFFFFFFF << 8) & 0xFFFFFFFF
print(ip & mask)
01AND keeps what the mask keeps
Where the mask has a 1, the network bit stays; where it has a 0, the result is 0. 192.168.1.77 AND 255.255.255.0 is 192.168.1.0.
02Broadcast fills the host bits
~mask flips every bit, giving ones in the host part. OR-ing them onto the network address gives the last address in the subnet: 192.168.1.255 for a /24.
print(subnet_info("10.20.30.130", 26)["broadcast"])10.20.30.19103Two addresses are reserved
A /26 has 2^6 = 64 addresses. The first identifies the network and the last is the broadcast address, which leaves 62 for devices.
Your turn
subnet_info(ip, prefix) for prefixes 1 to 30. Return a dictionary with "network" and "broadcast" as dotted strings and "hosts" as the number of usable host addresses. Calculate it yourself: do not import ipaddress in this lesson.What the checks look for
- Describes 192.168.1.77/24
- Describes 10.20.30.130/26
- Describes a /30 point-to-point link and a /20
- Does not use the ipaddress module
Take this with you
Network = address AND mask; broadcast = network OR inverted mask.
Go a little further
Add "first" and "last" keys for the first and last usable host addresses.