Back to index

glibc  2.9
Defines | Functions
gethostid.c File Reference
#include <alloca.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <netdb.h>
#include <not-cancel.h>
#include <string.h>
#include <sys/param.h>
#include <resolv/netdb.h>
#include <netinet/in.h>
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.


#define HOSTIDFILE   "/etc/hostid"


long int gethostid ()

Define Documentation

#define HOSTIDFILE   "/etc/hostid"

Definition at line 27 of file gethostid.c.

Function Documentation

long int gethostid ( )

Definition at line 71 of file gethostid.c.

  char hostname[MAXHOSTNAMELEN + 1];
  size_t buflen;
  char *buffer;
  struct hostent hostbuf, *hp;
  int32_t id;
  struct in_addr in;
  int herr;
  int fd;

  /* First try to get the ID from a former invocation of sethostid.  */
  fd = open_not_cancel (HOSTIDFILE, O_RDONLY|O_LARGEFILE, 0);
  if (fd >= 0)
      ssize_t n = read_not_cancel (fd, &id, sizeof (id));

      close_not_cancel_no_status (fd);

      if (n == sizeof (id))
       return id;

  /* Getting from the file was not successful.  An intelligent guess for
     a unique number of a host is its IP address.  Return this.  */
  if (__gethostname (hostname, MAXHOSTNAMELEN) < 0 || hostname[0] == '\0')
    /* This also fails.  Return and arbitrary value.  */
    return 0;

  buflen = 1024;
  buffer = __alloca (buflen);

  /* To get the IP address we need to know the host name.  */
  while (__gethostbyname_r (hostname, &hostbuf, buffer, buflen, &hp, &herr)
        != 0
        || hp == NULL)
    if (herr != NETDB_INTERNAL || errno != ERANGE)
      return 0;
      /* Enlarge buffer.  */
      buffer = extend_alloca (buffer, buflen, 2 * buflen);

  in.s_addr = 0;
  memcpy (&in, hp->h_addr,
         (int) sizeof (in) < hp->h_length ? (int) sizeof (in) : hp->h_length);

  /* For the return value to be not exactly the IP address we do some
     bit fiddling.  */
  return (int32_t) (in.s_addr << 16 | in.s_addr >> 16);

Here is the call graph for this function: