This post will discuss how to validate an IP address (IPv4) in C++. A valid IPv4 address must be in the form of xxx.xxx.xxx.xxx, where xxx is a number from 0-255.

For example,

'14.8.9.28', '255.255.255.255', '1.0.0.9' are valid IP addresses and

'100.xyz.1.15', '115.300.10.60', '50.35.6' are invalid IP addresses.

 
The idea is to split the given IP address to tokens using dot(.) as a delimiter. If the token size is not equal to 4, we return false; otherwise, we validate each token. If the token is not a number or the numbers are not in the valid range between 0 and 255, we return false. If all tokens are valid, we return true.

Following is a C++ implementation of the same:

Download  Run Code

Output:

Valid IP Address

 
We can also use any of the following implementations of the isNumber() function:

That’s all about validating an IP address in C++.

 
Also See:

Validate an IP address in Java