4

Why is the IPv4's decimal value different with inet_pton and inet_addr (1734763876) than what you get if you use these 2 websites (1684366951) ?

struct sockaddr_in sin;
inet_pton(AF_INET, "100.101.102.103", &(sin.sin_addr));
printf("%i\n%i\n", inet_addr("100.101.102.103"), sin.sin_addr);
Rup
  • 33,765
  • 9
  • 83
  • 112
Neeladri Vishweswaran
  • 1,695
  • 5
  • 22
  • 40

2 Answers2

7

Endianness - they have the four bytes in opposite orders:

1734763876 = 0x67 66 65 64
1684366951 = 0x64 65 66 67

The value you'll need to use for URLs etc. is the one in 'Network' order, Most-Significant-Byte first. Use htonl() (host-to-network-long) to convert the value, i.e.

printf("%i\n%i\n", htonl(inet_addr("100.101.102.103")), htonl(sin.sin_addr));

caf points out below that I probably have this backwards: the issue is really that you need to convert the network-order data from the socket functions back into host-order for display, i.e.

printf("%i\n%i\n", ntohl(inet_addr("100.101.102.103")), ntohl(sin.sin_addr));
Rup
  • 33,765
  • 9
  • 83
  • 112
  • 1
    Better to use `inet_ntop()` than `htonl` as it handles IPv6 too. – Jonathan Leffler Sep 29 '10 at 12:29
  • 1
    `inet_addr()` and `inet_ntop()` *are* creating a result in network byte order - the "problem" is just that the OP's `printf()` is interpreting them in host byte order. – caf Sep 29 '10 at 13:27
  • Oh, I've gotten that backwards? Thanks / oops - haven't programmed sockets for years. – Rup Sep 29 '10 at 13:43
1

inet_addr gives the result in network-byte order.

1684366951 and 1734763876 are the same number ;-) if you change the endianess.

harper
  • 13,345
  • 8
  • 56
  • 105