Some addresses have a special meaning. Sort addresses into the classes a network engineer would name.
What to build
A program that prints the class of each IPv4 address.
Requirements
invalidif the text is not four numbers from 0 to 255 separated by dots.- Otherwise, in this order:
loopback(first number 127),private(10.x.x.x, 172.16.x.x to 172.31.x.x, or 192.168.x.x),link-local(169.254.x.x),multicast(first number 224 to 239), andpublicfor everything else. - Print each address, a space, and its class.
Input
A line with n, then n lines, each one text with no spaces.
Output
n lines like 192.168.1.5 private.
Constraints
1 ≤ n ≤ 20.
Example
Input:
4
192.168.1.5
8.8.8.8
127.0.0.1
300.1.1.1
Output:
192.168.1.5 private
8.8.8.8 public
127.0.0.1 loopback
300.1.1.1 invalid
Why it works
Each special range is a prefix of the address bits, so checking the first one or two numbers is enough. Testing for a valid shape first keeps nonsense like 300.1.1.1 from being classed at all.
Examples
4 192.168.1.5 8.8.8.8 127.0.0.1 300.1.1.1
192.168.1.5 private 8.8.8.8 public 127.0.0.1 loopback 300.1.1.1 invalid
3 172.16.0.1 172.32.0.1 10.255.255.255
172.16.0.1 private 172.32.0.1 public 10.255.255.255 private
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Split at "." and check there are four parts that are all digits and at most 255.
Hint 2
Test the categories in the order given in the statement; the first one that fits wins.
Hint 3
172.16.0.0/12 means the second number is from 16 to 31.
Solution
Show one correct solution (try it yourself first)
n = int(input())
for _ in range(n):
ip = input().strip()
parts = ip.split(".")
ok = len(parts) == 4 and all(p.isdigit() and int(p) <= 255 for p in parts)
if not ok:
kind = "invalid"
else:
a, b = int(parts[0]), int(parts[1])
if a == 127:
kind = "loopback"
elif a == 10 or (a == 172 and 16 <= b <= 31) or (a == 192 and b == 168):
kind = "private"
elif a == 169 and b == 254:
kind = "link-local"
elif 224 <= a <= 239:
kind = "multicast"
else:
kind = "public"
print(ip, kind)
▶ Open this solution in the compiler, then press Visualize to watch it run step by step