Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

string

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.

like image 699
Bill the Lizard Avatar asked Nov 25 '08 17:11

Bill the Lizard


People also ask

How do you check IP address is IPv4 or IPv6 in C?

You could use inet_pton() to try parsing the string first as an IPv4 ( AF_INET ) then IPv6 ( AF_INET6 ). The return code will let you know if the function succeeded, and the string thus contains an address of the attempted type.


2 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.

like image 53
Raymond Martineau Avatar answered Sep 21 '22 19:09

Raymond Martineau


Boost.Asio provides the class ip::address. If you just want to verify the string, you can use it like this:

std::string ipAddress = "127.0.0.1"; boost::system::error_code ec; boost::asio::ip::address::from_string( ipAddress, ec ); if ( ec )     std::cerr << ec.message( ) << std::endl; 

This also works for hexadecimal and octal quads. This is also a much more portable solution.

like image 38
Björn Pollex Avatar answered Sep 25 '22 19:09

Björn Pollex