Thread: inet_pton problems

  1. #1
    Registered User
    Join Date
    Aug 2003

    inet_pton problems

    Using the following code to turn an ip address into a number, it doesn't output the correct numbers.
    #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)
    	return total;
    int main(int argc, char **argv)
    	char s[INET6_ADDRSTRLEN];
    	struct in_addr  ipv4;
    	struct in6_addr ipv6;
    	if(argc > 1)
    		fprintf(stderr,"Not enough args!\n");
    	errno = 0;
    	if(strcnt(s,':') > 1) // IPv6
    			printf("%s is %0llu (IPv6)\n",s,ipv6.s6_addr);
    			fprintf(stderr,"inet_pton IPv6 error: %d\n",errno);
    	else // IPv4
    			printf("%s is %0lu (IPv4)\n",s,ipv4.s_addr);
    			fprintf(stderr,"inet_pton IPv4 error: %d\n",errno);
    	return 0;
    $ ./pton is 16885952 (IPv4)
    $ ./pton ::ffff:
    ::ffff: is 13835052781062324224 (IPv6)
    $ ./pton 2001:DB8:2de::e13
    2001:DB8:2de::e13 is 13835052784150184224 (IPv6)
    As far as I know, is 3232235777, not what is output, and I assume the IPv6 address is incorrect as well. Any suggestions?
    Sigh, nothing ever works the first try.

    Register Linux User #314127

  2. #2
    Registered User
    Join Date
    Apr 2005
    The IP address in integer format is stored and printed in host-byte-order. You need to convert it to network-byte-order while printing it. Use macro htonl() to do this job. Changing printf stmt should be fine

    For e.g

    printf("%s is %0lu HEX: 0x%08X\n",s,htonl(ipv4.s_addr),htonl(ipv4.s_addr));
    My Output:

    C:\>pton is 3232235777 HEX: 0xC0A80101

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. No clue how to make a code to solve problems!
    By ctnzn in forum C Programming
    Replies: 8
    Last Post: 10-16-2008, 02:59 AM
  2. String Manipulation problems -_-
    By Astra in forum C Programming
    Replies: 5
    Last Post: 12-13-2006, 04:48 PM
  3. Rendering problems (DirectX?)
    By OnionKnight in forum Tech Board
    Replies: 0
    Last Post: 08-17-2006, 12:17 PM
  4. contest problems on my site
    By DavidP in forum Contests Board
    Replies: 4
    Last Post: 01-10-2004, 08:19 PM
  5. DJGPP problems
    By stormswift in forum C Programming
    Replies: 2
    Last Post: 02-26-2002, 03:35 PM
Website Security Test