tags:

views:

122

answers:

2

other than getdomainname() is there any way to get the domain name on Linux without having to open and parse files in /etc?

Code is appreciated.

Thanks

A: 

For future reference, Linux and some other systems have a getdomainname() function which should do what you want, although this is not part of the POSIX standard.

Tim
Thanks, but if you read my question you can see that I am aware of that function
wonderer
Yes, absolutely, but you and others who come here for an answer to the same question may value a reference to the documentation.
Tim
great thanks. I read the man when I was writing the code
wonderer
+1  A: 

Try the following:

#include <string.h>
#include <netdb.h>
#include <unistd.h>
#include <stdio.h>

int main(int argc, char* argv[])
{
  char hn[254];
  char *dn;
  struct hostent *hp;

  gethostname(hn, 254);
  hp = gethostbyname(hn);
  dn = strchr(hp->h_name, '.');
  if ( dn != NULL ) {
    printf("%s\n", ++dn);
  }
  else {
    printf("No domain name available through gethostbyname().\n");
  }

  return 0;
}

It seems that getdomainname() will only tell you a NIS or YP domain name, which you probably won't have set. Querying for the full hostname with gethostbyname(), on the other hand, checks a variety of different sources (including DNS and /etc/hosts) to determine your canonical hostname.

Niten
No the best solution since the hostname not always has the domain name but good enough
wonderer