Determining one's own IP address.

Mark Benard mb at rex.cs.tulane.edu
Wed Dec 13 02:52:04 AEST 1989


In article <604 at bmers58.UUCP> davem at bmers58.UUCP (Dave Mielke) writes:
>
>I would like to be able to determine my local IP address without
>involving a hosts file or yp lookup, i.e. from memory, from within a c
>program.

There is a library function gethostbyname() that will provide what you
want.  Below is a sample (but, sorry, undocumented) short C program that
uses to get the IP address given a full domain name.  You can shorten it
and hard-code your own host name into it.

Mark
----

/* gethostbyname : to get the IP address of the host */
/*          m. benard 11/88                          */

#include <stdio.h>
#include <netdb.h>

extern int h_errno;    /* needed for Pyramid OSx */

main(argc, argv)
int argc;
char *argv[];
{
    struct hostent *entp;
    unsigned char a, b, c, d;

    if (argc == 1) {
	printf ("Usage: gethostbyname host-name\n");
	exit();
	}
    entp = gethostbyname (argv[1]);
    if (entp <= 0) {
	if (h_errno == HOST_NOT_FOUND) {
	    printf ("Host not found\n");
	    exit();
	    }
	else if (h_errno == TRY_AGAIN) {
		printf ("No response from Internet nameserver.  Try again later.\n");
		exit();
		}
	     else {
		 printf ("Error %d\n", h_errno);
		 exit();
		 }
	}
    a = *((entp->h_addr)+0);
    b = *((entp->h_addr)+1);
    c = *((entp->h_addr)+2);
    d = *((entp->h_addr)+3);
    printf ("IP address: %u.%u.%u.%u\n", a, b, c, d);
    }
-- 
Mark Benard
Department of Computer Science     INTERNET & BITNET: mb at cs.tulane.edu
Tulane University                  USENET:   rex!mb
New Orleans, LA 70118



More information about the Comp.unix.wizards mailing list