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
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
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.
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.