/*
 * $Id: bootname.c,v 1.3 1995/02/01 12:56:29 casper Exp $
 *
 * Program to retrieve the hostname as found by bootparamd.
 * Two steps:
 *	- gethostbyname()
 *	- gethostbyaddr()
 *
 * Program may fail for multi-homed hosts.
 *
 * Casper Dik (casper@fwi.uva.nl)
 */

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <netdb.h>
#include <sys/utsname.h>

int
main(int argc, char **argv)
{
    struct hostent *hp;
    struct utsname name;
    char *hname;
    char b[4];

    if (argc > 2) {
	fprintf(stderr,"Usage: %s [hostname]\n", *argv);
	exit(1);
    }
    if (argc == 1) {
	if (uname(&name) == -1) {
	    perror("uname");
	    exit(1);
	}
	hname = name.nodename;
    } else
	hname = argv[1];

    if ((hp = gethostbyname(hname)) == NULL) {
	fprintf(stderr,"gethostbyname failed\n");
	exit(1);
    }

    /*
     * Apparently, the Solaris 2.4 gethostbyaddr call shares
     * its private memory with gethostbyname, this is unexpected.
     *
     * On the otehrhand, this bit of code is only needed for 2.3
     * and earlier.
     */
    memcpy(b, hp->h_addr_list[0], sizeof(b));

    if ((hp = gethostbyaddr(b,hp->h_length, hp->h_addrtype))
	    == NULL) {
	fprintf(stderr,"gethostbyaddr failed\n");
	exit(1);
    }
    printf("%s\n", hp->h_name);
    exit(0);
}
