Using the following code to turn an ip address into a number, it doesn't output the correct numbers.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <errno.h>
int strcnt(const char *str, char c)
{
int n = 0, total = 0;
for(; n < strlen(str); n++)
if(str[n] == c)
total++;
return total;
}
int main(int argc, char **argv)
{
char s[INET6_ADDRSTRLEN];
struct in_addr ipv4;
struct in6_addr ipv6;
if(argc > 1)
strncpy(s,argv[1],INET6_ADDRSTRLEN);
else
{
fprintf(stderr,"Not enough args!\n");
exit(-1);
}
errno = 0;
if(strcnt(s,':') > 1) // IPv6
{
if(inet_pton(AF_INET6,s,&ipv6.s6_addr))
printf("%s is %0llu (IPv6)\n",s,ipv6.s6_addr);
else
fprintf(stderr,"inet_pton IPv6 error: %d\n",errno);
}
else // IPv4
{
if(inet_pton(AF_INET,s,&ipv4.s_addr))
printf("%s is %0lu (IPv4)\n",s,ipv4.s_addr);
else
fprintf(stderr,"inet_pton IPv4 error: %d\n",errno);
}
return 0;
}
Code:
$ ./pton 192.168.1.1
192.168.1.1 is 16885952 (IPv4)
$ ./pton ::ffff:192.168.1.1
::ffff:192.168.1.1 is 13835052781062324224 (IPv6)
$ ./pton 2001:DB8:2de::e13
2001:DB8:2de::e13 is 13835052784150184224 (IPv6)
As far as I know, 192.168.1.1 is 3232235777, not what is output, and I assume the IPv6 address is incorrect as well. Any suggestions?