I wanted to know how I can parse an IPv6 address in C and convert it to a 128 bit value?
So a hex address like 1:22:333:aaaa:b:c:d:e
needs to be converted to its 128 bit equivalent binary. The problem is the IP address could be of the type ::2
and its variant since they are valid IPv6 address.
The input is from the keyboard and hence is in ASCII format.
You can use POSIX inet_pton
to convert a string to a struct in6_addr
.
#include <arpa/inet.h>
...
const char *ip6str = "::2";
struct in6_addr result;
if (inet_pton(AF_INET6, ip6str, &result) == 1) // success!
{
//successfully parsed string into "result"
}
else
{
//failed, perhaps not a valid representation of IPv6?
}