A packet filter accepts or drops traffic based on rules. For example, "allow TCP to port 80" or "drop ICMP type 8". Firewalls, IDS systems, and tcpdump all use this matching logic. The Berkeley Packet Filter (BPF) runs compiled filter programs in the kernel; this task builds a simplified user-space version.
Common Match Criteria
Protocol: TCP (6), UDP (17), ICMP (1)
IP addresses: source or destination like 192.168.1.0/24
Ports: e.g. destination port 443 for HTTPS
TCP flags: SYN-only for port scanning detection
A first-match policy processes rules in order with an implicit deny-all at the end.
User-Space Implementation
c
Loading…
Parse the IP protocol field, then drill into TCP or UDP headers for port numbers. For ICMP, check type and code instead of ports.
Why This Exercise
This task requires you to implement filter_packet() with protocol and port matching. The BPF you approximate here evolved into Linux eBPF, now powering Kubernetes networking and DDoS mitigation at scale. tcpdump still compiles expressions like tcp port 80 into this same match-and-drop logic before copying packets to user space.
Implement a C program that applies a first-match rule list to captured packets.
Input (stdin, whitespace-separated):
A line with R and P: number of rules, number of packets
R lines of rules: protocol (6=TCP, 17=UDP, 1=ICMP) and destination port (use 0 for ICMP rules or as a wildcard meaning "any port")
P lines of packets: protocol, source IP, destination IP (dotted quads), source port, destination port
Requirements:
Evaluate rules in order; the first matching rule decides the verdict (first-match policy with implicit deny-all at the end)
A rule matches when its protocol equals the packet protocol AND either its port is 0 (wildcard) or equals the packet's destination port. ICMP rules match on protocol alone
Print one verdict line per packet exactly as specified
Output format:
Per packet: "packet I proto=P SRC:SPORT->DST:DPORT accept" or "... drop" (I = zero-based index, IPs exactly as given)
Success Criteria:
First-match semantics: a later rule never overrides an earlier one
Port 0 acts as a wildcard; ICMP rules ignore ports entirely
Packets matched by no rule are dropped by the implicit deny-all