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

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.

Leave a Comment