A firewall holds a list of CIDR rules. Given the rules and one incoming IPv4 address, decide whether the address matches any rule. Use a bitwise trie (a binary trie over the address bits) so that prefix matching is fast.
Each rule is a string "A.B.C.D/prefix_length" that describes a network prefix. An address matches a rule when its first prefix_length bits equal the first prefix_length bits of the rule's network address A.B.C.D.
If at least one rule matches, return the matching rule with the shortest prefix length, as the exact string that appears in rules. If several matching rules share that shortest length, return the one that appears first in rules. If no rule matches, return the empty string "".
Function Signature
def firewall_match(rules: list[str], ip: str) -> str:
Rules
-
An address
A.B.C.D
is read as the 32-bit unsigned integer
(A << 24) | (B << 16) | (C << 8) | D
, and bits are compared from the most significant bit down.
-
Only the first
prefix_length
bits of a rule's network address count. The bits after the prefix may be nonzero and are ignored, so
"10.200.0.0/8"
covers the same addresses as
"10.0.0.0/8"
.
-
A rule with
prefix_length
0 matches every address.
-
The shortest matching prefix wins even when a longer matching rule comes earlier in the list. List order only breaks ties between matching rules of the same length.
Constraints
-
1 <= len(rules) <= 10^4
-
Each rule is a valid CIDR string of the form
"A.B.C.D/prefix_length"
-
0 <= prefix_length <= 32
-
0 <= A, B, C, D <= 255
-
ip
is a valid IPv4 address of the form
"A.B.C.D"
Examples
Input: rules = ["192.168.1.0/24", "10.0.0.0/8", "172.16.0.0/12"], ip = "192.168.1.100"
Output: "192.168.1.0/24"
The first 24 bits of 192.168.1.100 are 192.168.1, the same as the first rule's network. The other two rules start with the bytes 10 and 172, which differ from 192 in the first byte, so they do not match.
Input: rules = ["10.0.0.0/8", "10.10.0.0/16", "10.10.10.0/24"], ip = "10.10.10.5"
Output: "10.0.0.0/8"
All three rules match 10.10.10.5. The /8 rule has the shortest prefix, so it is the answer.
Input: rules = ["10.1.0.0/16", "10.200.0.0/8", "10.0.0.0/8"], ip = "10.1.2.3"
Output: "10.200.0.0/8"
All three rules match. Two of them have the shortest length, 8, and both cover every 10.x.x.x address because only the first 8 bits count; "10.200.0.0/8" comes first among them. The /16 rule is earlier in the list, but its prefix is longer.