Given an address with a prefix length, print its network address, broadcast address, first and last usable host, and the number of usable hosts.
Input
One line: an IPv4 address and prefix length, like 192.168.1.10/26 (0 ≤ prefix ≤ 30).
Output
Five lines, exactly like this:
network 192.168.1.0
broadcast 192.168.1.63
first 192.168.1.1
last 192.168.1.62
hosts 62
Examples
Example 1 · Input
192.168.1.10/26
Expected output
network 192.168.1.0 broadcast 192.168.1.63 first 192.168.1.1 last 192.168.1.62 hosts 62
Example 2 · Input
10.0.0.1/8
Expected output
network 10.0.0.0 broadcast 10.255.255.255 first 10.0.0.1 last 10.255.255.254 hosts 16777214
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Turn the address into one 32-bit number: n = n * 256 + part for each part.
Hint 2
mask = (0xFFFFFFFF << (32 - p)) & 0xFFFFFFFF; network = address & mask; broadcast = network | (~mask & 0xFFFFFFFF).
Hint 3
Hosts = 2 ** (32 - p) - 2, from network + 1 to broadcast - 1.
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
def to_ip(n):
return ".".join(str((n >> s) & 255) for s in (24, 16, 8, 0))
ip, prefix = input().strip().split("/")
p = int(prefix)
mask = (0xFFFFFFFF << (32 - p)) & 0xFFFFFFFF
network = to_number(ip) & mask
broadcast = network | (~mask & 0xFFFFFFFF)
print("network", to_ip(network))
print("broadcast", to_ip(broadcast))
print("first", to_ip(network + 1))
print("last", to_ip(broadcast - 1))
print("hosts", 2 ** (32 - p) - 2)