get_machine_name.c

Go to the documentation of this file.
00001 
00007 /* $Id: get_machine_name.c,v 1.12 2006/02/15 16:43:15 seymour Exp $ */
00008 /* $UTK_Copyright: $ */
00009 
00010 #include <stdlib.h>
00011 #include <string.h>
00012 
00013 #include "portability.h"
00014 #include "utility.h"
00015 #include "proxylib.h"
00016 
00017 #define GS_HOST_NAME_MAX 1024
00018 #define GS_DOMAIN_NAME_MAX 1024
00019 
00020 char *gs_fallback_get_machine_name();
00021 
00028 char *
00029 gs_get_machine_name()
00030 {
00031   const unsigned char *p;
00032   static char buf[16];
00033   struct hostent *hp;
00034   ipaddr_t myip; 
00035 
00036   myip = proxy_get_my_ipaddr();
00037 
00038   p = (const unsigned char *) &myip;
00039   sprintf(buf, "%u.%u.%u.%u",
00040           (unsigned int) (p[0] & 0xff), (unsigned int) (p[1] & 0xff),
00041           (unsigned int) (p[2] & 0xff), (unsigned int) (p[3] & 0xff));
00042 
00043   if(myip > 0) {
00044     if((hp = gethostbyaddr((char*)&myip, sizeof(myip), AF_INET)) != NULL) {
00045       if(!strstr(hp->h_name, ".")) {
00046         hp = gethostbyname(hp->h_name);
00047         if(hp && strstr(hp->h_name, "."))
00048           return strdup(hp->h_name);
00049       }
00050       else
00051         return strdup(hp->h_name);
00052     }
00053   }
00054 
00055   /* if the above failed, fall back to the old method */
00056 
00057   return gs_fallback_get_machine_name();
00058 }
00059 
00060 char *
00061 gs_fallback_get_machine_name()
00062 {
00063   char name[GS_HOST_NAME_MAX], domain[GS_DOMAIN_NAME_MAX],
00064      hostname[GS_HOST_NAME_MAX+GS_DOMAIN_NAME_MAX], *retval;
00065 
00066   if(gethostname(name, GS_HOST_NAME_MAX-1) == -1)
00067     return(strdup("localhost.localdomain"));
00068 
00069   name[GS_HOST_NAME_MAX-1] = 0;
00070 
00071   if(strlen(name) == 0)
00072     sprintf(name, "localhost");
00073 
00074   if(!strstr(name,".")) {
00075     if(getdomainname(domain, GS_DOMAIN_NAME_MAX-1) == -1)
00076       return(strdup("localhost.localdomain"));
00077 
00078     domain[GS_DOMAIN_NAME_MAX-1] = 0;
00079 
00080     if((strlen(domain) == 0) || !strcmp(domain, "(none)"))
00081       sprintf(domain, "localdomain");
00082 
00083     sprintf(hostname, "%s.%s", name, domain);
00084 
00085     retval = strdup(hostname);
00086   }
00087   else
00088     retval = strdup(name);
00089 
00090   return retval ? retval : strdup("localhost.localdomain");
00091 }