-1

I'm trying to get a string with the ip address in dotted decimal of my machine. What I do is trying to get the string from INADDR_LOOPBACK with the following code.

char addr[INET_ADDRSTRLEN];
struct in_addr *in_addr1 = malloc(sizeof(struct in_addr));
in_addr1->s_addr = INADDR_LOOPBACK;
inet_ntop(AF_INET, in_addr1, addr, INET_ADDRSTRLEN);
printf("addr: %s\n", addr);

Here's what I get from the printf:

1.0.0.127

  1. Why is it the localhost address reverse? Should it print 127.0.0.1?
  2. Honestly I was expecting to get the ip I would get calling for example $ ifconfig... not the localhost! Did I misunderstand what INADDR_LOOBACK does?
Robb1
  • 4,587
  • 6
  • 31
  • 60
  • Unrelated to your problem, but why do you allocate the `in_addr` structure dynamically? Why not define it as e.g. `struct in_addr in_addr1;`? And then use the address-of operator `&` when passing to `inet_ntop`? – Some programmer dude Oct 04 '17 at 17:07
  • As for your problem, remember that the address is supposed to be in *network byte order*. See e.g. [this `inet_ntop` manual page](http://man7.org/linux/man-pages/man3/inet_ntop.3.html). – Some programmer dude Oct 04 '17 at 17:09
  • @Someprogrammerdude for no special reason... I'm just used to do in this way. Would defining it as you say be an improvement in performance / something else? – Robb1 Oct 04 '17 at 17:09
  • Well not using pointer and dynamic allocation will mean less risk of dereferencing null or invalid pointers, or having memory leaks. – Some programmer dude Oct 04 '17 at 17:09
  • Quite probably a dupe of https://stackoverflow.com/questions/212528/get-the-ip-address-of-the-machine – fvu Oct 04 '17 at 17:10
  • 2
    Get unused to doing it that way. Allocating memory dynamically when a simple local variable will suffice is a terrible practice that would never survive a competent code review. – Carey Gregory Oct 04 '17 at 17:12

1 Answers1

1

INADDR_LOOPBACK is in host byte order, i.e. 0x7f000001. It is, incidentally, the IPv4 address 127.0.0.1.

in_addr1->s_addr must be in network byte order.

Your computer is a little-endian computer where the host byte order doesn't match the network byte order. You must use htonl to convert the loopback address to network byte order.