Get the domain name in linux (C programming)
other than getdomainname() is there any way to get the domain name开发者_Go百科 on Linux without having to open and parse files in /etc?
Code is appreciated.
Thanks
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.
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.
#include <stdio.h>
#include <netdb.h>
#include <sys/socket.h>
#include <arpa/inet.h>
int main(int argc, char *argv[])
{
int i;
struct hostent *he;
struct in_addr **addr_list;
if (argc != 2) {
fprintf(stderr,"usage: ghbn hostname\n");
return 1;
}
if ((he = gethostbyname(argv[1])) == NULL) {
herror("gethostbyname");
return 2;
}
printf("domain name is: %s\n", he->h_name);
printf(" IP addresses: ");
addr_list = (struct in_addr **)he->h_addr_list;
for(i = 0; addr_list[i] != NULL; i++) {
printf("%s ", inet_ntoa(*addr_list[i]));
}
printf("\n");
return 0;
}
run command:
gcc -o test test.c
./test www.google.com
Output:
domain name is: google.com
IP addresses: 172.217.163.110
精彩评论