cybersecurity · intermediate · ~15 min · safe pentest lab
Walk a static XML buffer with string functions and count specific tags.
Count the open ports in a saved nmap XML dump — defenders read scan output far more often than they run scans.
Implement int count_open_ports(const char *xml) that returns how many <port ...> elements are open (their inner <state state="open"/>). Skip closed and filtered ports.
xml: a NUL-terminated string holding saved nmap XML, baked into the harness. It is never live nmap output.Returns a non-negative int: the number of open ports.
"" -> 0
one open port -> 1
two open + one filtered -> 2
<port> tags, returns 0.state="open" look-ahead by the next <port so a later open port can't be credited to an earlier filtered one. Match the closing quote so state="open|filtered" does not count.Defenders read scan output far more often than they run scans. A 20-line strstr walker is the canonical way to do it.
A NUL-terminated XML string.
A non-negative int — the count.
No allocation. No XML library. Pure scan.
#include <stddef.h>
#include <string.h>
int count_open_ports(const char *xml) {
/* TODO */
(void)xml;
return 0;
}
Matching state="open as a substring (catches "open|filtered"). Forgetting to bound the look-ahead.
Empty string. No <port> tags. All closed/filtered. Malformed (unclosed tag) — count what you can.
O(n) — single pass.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.