networking · beginner · ~10 min · safe pentest lab

Parse an IPv4 address

Parse a dotted-quad IPv4 string into its 32-bit big-endian value.

Challenge

Before a client can connect(), it must turn a dotted-quad string into the 32-bit address a sockaddr_in holds. Implement that parse:

int parse_ipv4(const char *s, uint32_t *out);

Return 1 and set *out to a<<24 | b<<16 | c<<8 | d (network/big-endian order) for a valid "a.b.c.d"; return 0 for anything malformed.

Why this matters

The full client prologue: socket → fill sockaddr_in → connect.

Input format

A NUL-terminated string.

Output format

1 + *out set on success; 0 on malformed input.

Constraints

Each octet is 0–255. Exactly four octets. No leading zeros, no signs, no trailing characters.

Starter code

#include <stdint.h>
/* Parse a dotted-quad IPv4 like "192.168.1.1" into *out as a big-endian
   uint32 (a<<24|b<<16|c<<8|d). Return 1 on success, 0 if malformed. Each octet
   must be 0..255, exactly four, no leading zeros, no extra chars. */
int parse_ipv4(const char *s, uint32_t *out){ (void)s;(void)out; return 0; }

Common mistakes

Forgetting the leading-zero rule; letting an octet exceed 255; accepting trailing junk after the fourth octet.

Edge cases to handle

"0.0.0.0" and "255.255.255.255" are valid; "256.1.1.1", "1.2.3", "01.2.3.4" are not.

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.