cybersecurity · intermediate · ~15 min · safe pentest lab
Walk a static XML buffer with string functions and count specific tags.
Implement int count_open_ports(const char *xml).
It walks the buffer and returns the number of <port ...> elements whose
inner <state state="open"/> indicates the port is open. Skip filtered
and closed.
int count_open_ports(const char *xml);
| Input | Returns |
|---|---|
"" |
0 |
| One open port | 1 |
| Two open + one filtered | 2 |
strstr(p, "<port") finds the next port element.<port, look ahead within the same element (bounded by the next <port or a fixed window) for state="open".state="open" as a substring also catches state="open|filtered" in some old nmap versions. Use exact quote-bounded match.This exercise is for defensive learning in a local lab only. Do not use any variant of this technique on systems you do not own or have explicit permission to test.
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.