Validate IPv4 Address

Description: Simple validation for IP addresses in v4 format. Does not validate octal or hex quads. Requires <sstream> to be included and using standard namespace.
Tested Platform: Visual Studio 2012, 32-bit, Windows 7
Language: C/C++
// Validates standard v4 IP address strings from "0.0.0.0" to "255.255.255.255"
// Returns true if IP Address is valid, otherwise false.

bool validateIPv4(string IPAddress) {
    istringstream ss(IPAddress);
    string octet;
    int octetcount = 0;

    while (ss)
    {
        if (!getline(ss, octet, '.')) { break; }
        istringstream octetstream(octet);

        int ioctet;
        octetstream >> ioctet;

        if ((!octetstream) || (octetstream.peek() != EOF) || (ioctet < 0) || (ioctet > 255)) {
            return false;
        }

        octetcount++;
    }

    if (octetcount != 4) { return false; }

    return true;
}

Submitted: February 10, 2014

Return to the snippets listing