How do you validate that a string is a valid IPv4 address in C++?

Viewed 96870

I don't need to validate that the IP address is reachable or anything like that. I just want to validate that the string is in dotted-quad (xxx.xxx.xxx.xxx) IPv4 format, where xxx is between 0 and 255.

17 Answers

You probably want the inet_pton, which returns -1 for invalid AF argument, 0 for invalid address, and +1 for valid IP address. It supports both the IPv4 and future IPv6 addresses. If you still need to write your own IP address handling, remember that a standard 32-bit hex number is a valid IP address. Not all IPv4 addresses are in dotted-decimal notation.

This function both verifies the address, and also allows you to use the same address in related socket calls.

The solution that I settled on was:

#include <arpa/inet.h>
// ...
bool Config::validateIpAddress(const string &ipAddress)
{
    struct sockaddr_in sa;
    int result = inet_pton(AF_INET, ipAddress.c_str(), &(sa.sin_addr));
    return result != 0;
}

This works for most cases that were mentioned in other answers. It doesn't recognize IP addresses with octal or hex formatting, but that's acceptable for my application.

This looks deceptively simple but has a few pitfalls. For example, many of the solutions posted in the previous answers assume that the quads are in base 10 - but a quad starting with a zero must be treated as a base 8 (octal) number, hence for example any quad part starting with zero and containing the digits 8 or 9 is not valid. I.e, the IP number 192.168.1.010 is not 192.168.1.10 but in reality is 192.168.1.8, and the IP number 192.168.019.14 is not valid since the third quad contains the invalid base 8 digit 9.

I emphatically encourage you to use the functions provided by the socket library included in your operating system or compiler environment.

Edit: (Thought it was implicit, but) of course, you can also have hexadecimal quads, a la 192.168.1.0x0A for 192.168.1.10, and of course you can mix and match to your sadistic content happily using upper and lower case, a la 0xC0.0xa8.1.010 for 192.168.1.8. Try some examples using ping if you want to have fun. This works just fine cross-platform (tested a while back while swearing under Linux, NetBSD, and Win32.)

Further edit in response to KaluSingh Gabbar's request: For example, you can specify 192.168.1.10 as 0xc0a8010a and it still represents a valid IP number, a la:

[mihailim@home ~]$ ping 0xc0a8010a
PING 0xc0a8010a (192.168.1.10) 56(84) bytes of data.
^C
--- 0xc0a8010a ping statistics ---
3 packets transmitted, 0 received, 100% packet loss, time 2479ms

Here's one straightforward method.

bool IsIPAddress(std::string & ipaddr)
    {    

    StringTokenizer quads(ipaddr,".");

    if (quads.countTokens() != 4) return false;

    for (int i=0; i < 4; i++)
      {
      std::string quad = quads.nextToken();
      for (int j=0; j < quad.length(); j++
         if (!isdigit(quad[j])) return false;

      int quad = atoi(quads.GetTokenAt(i));
      if (quad < 0) || (quad > 255)) return false;
      }

    return true;
    }

You can write your own function like this:

bool isValidIPv4(const char *IPAddress)
{
   unsigned char a,b,c,d;
   return sscanf(IPAddress,"%d.%d.%d.%d", &a, &b, &c, &d) == 4;
}

sscanf() and sprintf() are very useful in some situation. :))

Boost.Regex would be appropriate.

bool validate_ip_address(const std::string& s)
{
   static const boost::regex e("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}");
   return regex_match(s, e);
}

If you wanted to write this yourself rather than use a library then

atoi() to convert characters to ints will let you test the range of each number, and some strcmp's between the "."'s. You can also do some quick checks, such as the length of the string (should be less than 16 characters (not including null terminator), number of dots. etc.

But, it's probably MUCH easier to use existing code.

If you don't want the overhead of Boost or TR1 you could search for the dots and check if the characters between them are numbers from 0 to 255.

If you wish to receive an IP address in the usual form (8.8.8.8, 192.168.1.1, etc...) Then I've written the following code that expands on Bjorn's answer:

void validateIP(const std::string &IPv4_address)
{
    boost::system::error_code error_code;
    auto raw_ipv4_address = boost::asio::ip::address::from_string(IPv4_address, error_code);
    if (error_code)
    {
        throw std::invalid_argument(error_code.message());
    }

    std::string raw_to_string_form = raw_ipv4_address.to_string();
    if (raw_to_string_form.compare(IPv4_address))
    {
        throw std::invalid_argument("Input IPv4 address is invalid");
    }
}

The reason being is that if you pass on an IP such as 8.88.8, or 12345 (decimal form), Bjorn's answer won't throw an error. (at least with boost 1.68) My code converts any form to the internal structure in Boost, then converts it back to a dotted-decimal format, we then compare it to the first IP we received to see if they are equal, if not, we know for sure that the input is not the way we wanted it.

void validate_ip_address(const std::string& s) {
    const std::string number_0_255 = "((([0-9])|([1-9][0-9])|(1[0-9][0-9]|2[0-4][0-9]|25[0-5])){1})";
    const std::string dot = "(\\.){1}";
    static const boost::regex e(number_0_255 + dot + number_0_255 + dot + number_0_255 + dot + number_0_255);
    if (!regex_match(s, e)) {
        throw std::runtime_error(std::string("Uncorrect address IP: ") + s);
    }
}
Related