Finding your remote host's name

Wietse Venema wswietse at lso.win.tue.nl
Thu Jun 7 19:04:12 AEST 1990


scm at dlcq15.datlog.co.uk (Steve Mawer) writes:

>If I `rlogin' from machine1 to machine2, is there a simple and (relatively)
>portable way to find out on machine2 the name of machine1?  I'd like to do
>this from a shell script if possible, but I'm willing to write C code if
>necessary.

/* fromhost - print name of host we are logged in from */

#include <stdio.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/socket.h>
#include <syslog.h>
#include <netinet/in.h>
#include <netdb.h>

#ifndef	MAXHOSTNAMELEN
#define	MAXHOSTNAMELEN	BUFSIZ		/* BSD 4.2 ?? */
#endif

main(argc, argv)
int     argc;
char  **argv;
{
    int     length;
    struct sockaddr sa;
    struct sockaddr_in *sin = (struct sockaddr_in *) (&sa);
    char    host_name[MAXHOSTNAMELEN];
    struct hostent *hp;
    char   *inet_ntoa();
    void    exit();
    void    syslog();

    length = sizeof(sa);

    if (getpeername(0, &sa, &length) >= 0) {
	if (sa.sa_family == AF_INET) {
	    if (hp = gethostbyaddr((char *) &sin->sin_addr.s_addr,
				   sizeof(sin->sin_addr.s_addr), AF_INET))
		(void) printf("%s\n", hp->h_name);
	    else
		(void) printf("%s\n", inet_ntoa(sin->sin_addr));
	    exit(0);
	}
    }
    exit(1);
}



More information about the Comp.unix.questions mailing list