The first step of every route lookup is asking whether a destination matches a network.
What to build
A program that says whether an address belongs to a network.
Requirements
- Compare the first prefix-length bits of the address with those of the network.
- Print
yesif they are equal, otherwiseno.
Input
Line 1: an IPv4 address. Line 2: a network as address/prefix.
Output
yes or no.
Constraints
0 ≤ prefix ≤ 32. The network address may have host bits set; ignore them.
Example
Input:
10.1.2.7
10.1.0.0/16
Output:
yes
Why it works
The prefix says how many leading bits name the network, so two addresses are in the same network exactly when those bits are equal. ANDing both with the mask throws the other bits away.
Examples
10.1.2.7 10.1.0.0/16
yes
10.2.2.7 10.1.0.0/16
no
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Turn both addresses into 32-bit numbers: n = n * 256 + part.
Hint 2
mask = (0xFFFFFFFF << (32 - p)) & 0xFFFFFFFF.
Hint 3
The address is inside when address & mask equals network & mask.
Solution
Show one correct solution (try it yourself first)
def to_number(ip):
n = 0
for part in ip.split("."):
n = n * 256 + int(part)
return n
ip = input().strip()
net, prefix = input().strip().split("/")
p = int(prefix)
mask = (0xFFFFFFFF << (32 - p)) & 0xFFFFFFFF
print("yes" if to_number(ip) & mask == to_number(net) & mask else "no")
▶ Open this solution in the compiler, then press Visualize to watch it run step by step