cybersecurity · intermediate · ~15 min
Practise parsing a foundational structure that's a popular attack surface.
Parse a simple http/https URL into its parts, defaulting the port and rejecting malformed input.
The grader supplies this struct (do not redefine it):
typedef struct {
char scheme[8]; // "http" or "https"
char host[128]; // hostname (no port)
int port; // 80/443 by default
char path[256]; // "/" if not present
} url_t;
Implement int parse_http_url(const char *url, url_t *out) that fills out from a URL of the form scheme://host[:port][/path]. No main — the grader calls it.
url: the URL string to parse.out: a url_t to populate.Returns 0 on success (with out filled), or -1 on failure. Defaults: port 80 for http, 443 for https; path "/" when none is present.
"http://example.com/path" -> scheme="http", host="example.com", port=80, path="/path"
"https://api.example.org/v1" -> scheme="https", port=443, path="/v1"
"http://host:8080/" -> port=8080
"ftp://x/y" -> -1 (bad scheme)
"http://x:abc/" -> -1 (bad port)
"/".:// separator, then parse host, optional :port, optional /path. Bound every copy to its destination size.A URL string and a url_t out struct to populate.
0 with out filled on success, -1 on failure; port and path default when absent.
Only http/https; host <= 127 chars; valid port; bound every copy; do not redefine url_t.
#include <string.h>
#include <stdio.h>
int parse_http_url(const char *url, url_t *out) {
/* TODO */
return -1;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.