Thread: inet_pton problems

  1. #1
    Registered User
    Join Date
    Aug 2003
    Posts
    42

    inet_pton problems

    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?
    Sigh, nothing ever works the first try.

    Register Linux User #314127

  2. #2
    Registered User
    Join Date
    Apr 2005
    Posts
    134
    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

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

    C:\>pton 192.168.1.1
    192.168.1.1 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, 05: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, 09:19 PM
  5. DJGPP problems
    By stormswift in forum C Programming
    Replies: 2
    Last Post: 02-26-2002, 04:35 PM