IP address validation

Q. How to validate an IP address (IPv4 or IPv6), given as a string input ?

Ans: Using regex is not good idea. Rather use function inet_pton to do the validation task. The pseudo code for IP address validation is as below:

bool
isValidIPAddress(
    IN char *ipAddr
    )
{
    unsigned char buf[sizeof(struct in6_addr)];
    int ret;

    ret = inet_pton(AF_INET, ipAddr, buf);
    if (1 == ret) {
        return true;
    }

    ret = inet_pton(AF_INET6, ipAddr, buf);
    if (1 == ret) {
        return true;
    }
    return false;
}

Advertisements