wonderer
wonderer

Reputation: 3557

Get the domain name in linux (C programming)

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

Upvotes: 2

Views: 7813

Answers (3)

Shrikant Pardhi
Shrikant Pardhi

Reputation: 1

#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

Upvotes: 0

mshroyer
mshroyer

Reputation: 1968

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.

Upvotes: 3

Tim
Tim

Reputation: 9259

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.

Upvotes: 0

Related Questions