/* sivann 95 */
/* display your remote host taken from utmp */
/* compile like this: 
 * gcc -O whereami.c -o whereami
 *
 */

#include       <stdio.h>
#include       <unistd.h>
#include       <sys/types.h>
#include       <utmpx.h>
#include       <pwd.h>
#include 	<fcntl.h>

//#define        UTMPX    "/etc/utmpx"
#define        UTMPX    "/var/run/utmp"

main(ac, av)
  char           *av[];
  int             ac;
{
  int             ud;
  struct utmpx    ur;
  struct passwd  *pw;
  char            tty[32];

  if (ac == 2) {
    printf("%s, used to set the DISPLAY variable\n"
	   "Spiros Ioannou 1995\n", av[0]);
    exit(2);
  }
  if ((ud = open(UTMPX, O_RDONLY)) < 0) {
    perror(UTMPX);
    exit(1);
  }
  pw = getpwuid(getuid());
  while (read(ud, &ur, sizeof(struct utmpx)) == sizeof(struct utmpx)) {
    tty[0] = '\0';
    strcpy(tty, "/dev/");
    strcat(tty, ur.ut_line);

    if (strcmp(pw->pw_name, ur.ut_user) == 0 && strcmp(tty, ttyname(0)) == 0) {
      printf("%s\n", ur.ut_host);
      exit(0);
    }
  }
}

