3

I want to understand in which order are the elements of h_addr_list sorted when I get the hostent from gethostbyname.

Basically, I'm working on a very old function that gets a hostent struct from gethostbyname, and returnes h_addr to the caller. I'm trying to figure out which address will be returned in case of multiple active interfaces.

Google and source-code browsing could not help me here. Is there documentation or some information on the order of h_addr_list?

P.S. I'm working on code for both Windows and Linux.

Eitan T
  • 32,660
  • 14
  • 72
  • 109
Neowizard
  • 2,981
  • 1
  • 21
  • 39
  • Not an answer because I'm not sure if it applies here, but for dns queries at least it's common to "shuffle" the order for each request so that if a server has more than one address they'll all get some use. Meaning that the order is essentially random for each request and not something you can rely on. – jcoder Jun 21 '12 at 08:22
  • 1
    Neither the official manual page for [`gethostbyname`](http://pubs.opengroup.org/onlinepubs/009695399/functions/gethostbyname.html) or of the [``](http://pubs.opengroup.org/onlinepubs/009695399/basedefs/netdb.h.html) defines an order. So my guess is that there is no order, and that it might even change between calls. – Some programmer dude Jun 21 '12 at 08:24
  • 2
    If you are laying hands on this part of a program, you should consider rewriting it to use `getaddrinfo()` and `getnameinfo()`, as appropriate. This would make the program future-proof. – glglgl Jun 21 '12 at 09:19
  • I agree, I wish I could update that entire lib, let alone that one function, but it's *way* out of our current scope. – Neowizard Jun 21 '12 at 09:42

1 Answers1

2

What makes you think that there is "an order" in the first place? What would make any particular address more worthy of being listed first?

In other words, I don't think there is a well-defined order for the addresses. You simply get all the addresses that are available to the lookup system.

unwind
  • 391,730
  • 64
  • 469
  • 606
  • I figured that there's some arbitrary ordering (i.e. lowest lexicographic mac-address first), just because I assume an order would be preferable to lack thereof. – Neowizard Jun 21 '12 at 08:28