Validate an IP address in C++

In this post, we will see 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 into tokens by using dot(.) as a delimiter. If the token size is not equal to 4, we return false else we validate each token. If token is not a number or the numbers are not in the valid range between 0 to 255, we return false. If all tokens are valid, we return true.

Below is C++ implementation of the same:

 

Download   Run Code

Output:

Valid IP Address

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

 

 

 

 
Also See: Validate IP address in Java (6 methods)

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz