10

Ok before posting this question I have checked threads here in_addr_t to string

my question is different.

I understand that inet_ntoa function is of following type

char * inet_ntoa (struct in_addr in);

What I want to know is what is in_addr_t

what will be the representation when it is used in a socket program.

I checked the structure definition in <netinet/in.h>

   typedef uint32_t in_addr_t;

   struct in_addr {
       in_addr_t s_addr;
   };

is of above type. I do not want to print in_addr_t to char * as inet_ntoa does. I want to see what is in_addr_t.So how can it be done or what exactly is in_addr_t and why is it used again and again in socket programming. If I am not mistaken it is defined as

typedef uint32_t in_addr_t;

So if in_addr_t is unsigned 32 bit int I want to see what is that and not the char * which prints 192.168.1.1 kind of output on stdout.

Community
  • 1
  • 1
Registered User
  • 5,173
  • 16
  • 47
  • 73
  • Based on the questions you've been asking I recommend you pick up a book like the classic *Internetworking with TCP/IP* by Comer. – Ben Jackson Jun 30 '11 at 06:15

2 Answers2

18

As we all know (we do, right?) an IPv4 address is represented using an unsigned 32 bits integer. Us puny humans aren't so good with large numbers (or small ones) so we use dot decimal notation. (Did you know you're at 1076000524 right now ? Neither did I).

However, since you dug through netinet and found out what is clearly specified by the standard

The <netinet/in.h> header shall define the in_addr structure, which shall include at least the following member:

in_addr_t s_addr

Which is

in_addr_t Equivalent to the type uint32_t as described in <inttypes.h>

you can print it.

printf("My unreadable addres is %u\n", in.s_addr);

Quick, what does 134744072 stand for ?

cnicutar
  • 178,505
  • 25
  • 365
  • 392
  • 3
    You didn't specify the most important thing - byte order. Everything else is obvious. – Simon Feb 24 '14 at 23:22
  • @Simon Can you expand on that ? – cnicutar Feb 24 '14 at 23:42
  • 2
    @cnicutar Network byte order is big-endian. You must use use functions like `htons`/`htonl` ("host to network, short/long") or `ntohs`/`ntohl` ("network to host, short/long") to get the correct values regardless of the architecture. – Diti May 14 '14 at 20:38
  • btw, result for `134744072` is the same regardless of the endianess :) – mathway Dec 18 '22 at 16:00
0

You must translate 134744072 in hex using:

printf("My unreadable address is %lX\n", in.s_addr);

Use %lX for long unsigned hexadecimal. This address is: 8.8.8.8

Igor
  • 1,582
  • 6
  • 19
  • 49
phil91
  • 1
  • 2