Issue 7 of posix removed gethostbyname, so I can no longer do gethostbyname("my_hostname") to get canonical hostname for my machine. I've tried to use getnameinfo instead, but given /etc/hosts like localhost my_hostname.fqdn my_hostname

I'm getting back localhost (which makes sense). However gethostbyname("my_hostname") does return my_hostname.fqdn (at least both under musl and glibc).

Is there a reasonable replacement for my use case in issue 7 or am I out of luck on this one?

  • 2
    How would you define the “canonical” hostname for a machine? – Stephen Kitt Mar 11 at 22:49
  • What IETF calls "hostname" is just one of the names associated to a network interface... there could be hundreds (think webhosting). – vonbrand Mar 12 at 1:22
  • @StephenKitt basically mirror behaviour of hostname -f; canonical hostname as described in hosts(5) – graywolf Mar 12 at 14:48
  • But hosts(5) defines canonical hostnames for IP addresses, not for a machine. – Stephen Kitt Mar 12 at 15:21

From the Solaris man page:

 These functions are used to obtain entries describing hosts.
 An  entry  can come from any of the sources for hosts speci-
 fied in the /etc/nsswitch.conf file.  See  nsswitch.conf(4).
 These      functions     have     been     superseded     by
 getipnodebyname(3SOCKET),   getipnodebyaddr(3SOCKET),    and
 getaddrinfo(3SOCKET),  which  provide greater portability to
 applications when multithreading is performed  or  technolo-
 gies  such  as  IPv6  are  used.  For example, the functions
 described in the following cannot be used with  applications
 targeted to work with IPv6.

As you see, the function getaddrinfo() is also in the POSIX standard and supported...

| improve this answer | |

The current POSIX-compliant way to (try to) determine the current host’s “canonical” FQDN is to call gethostname() to determine the configured hostname, then getaddrinfo() to determine the corresponding address information.

Ignoring errors:

char buf[256];
struct addrinfo *res, *cur;
struct addrinfo hints = {0};
hints.ai_family = AF_UNSPEC;
hints.ai_flags = AI_CANONNAME;
hints.ai_socktype = SOCK_DGRAM;

gethostname(buf, sizeof(buf));
getaddrinfo(buf, 0, &hints, &res);
for (cur = res; cur; cur = cur->ai_next) {
    printf("Host name: %s\n", cur->ai_canonname);

The results are highly dependent on the system and resolver configuration.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.