/* gethostbyname.c: illustrate the use of gethostbyname function. compile: cc -c gethostbyname.c -lnsl */ #include #include #include #include #include #include #include #include /* ----------------------------------------------------------------- paddr: print the IP address in a standard decimal dotted format ----------------------------------------------------------------- */ void paddr(unsigned char *a) { printf("%d.%d.%d.%d", a[0], a[1], a[2], a[3]); } int main() { char hname[100]; struct hostent *hp; /* host pointer */ char **p; /* help variable to access h_aliases[ ] */ int **a; /* Help variable to access h_addr_list[ ] */ int addr; int i; printf("Enter hostname: "); scanf("%s", hname); hp = gethostbyname(hname); if (hp == NULL) { printf("host information for %s not found\n", hname); exit(1); } printf("official hostname h_name = `%s'\n", hp->h_name); printf("Host has this alias list:\n"); p = hp->h_aliases; // p[i] is a string (char *) for ( i = 0 ; p[i] != NULL; i++ ) { printf("\tAlias %d: %s\n", i+1, p[i]); } /* ---------------------------------------------- * This is how to use incrementing pointer.... * for (p = hp->h_aliases; *p != 0; p++) { printf("\t%s\n", *p); } */ printf("Host's address type = %d (should be AF_INET = %d)\n", hp->h_addrtype, AF_INET); printf("Host's address length = %d\n", hp->h_length); printf("List of Internet addresses for host:\n"); a = (int **) hp->h_addr_list; for (i = 0; a[i] != 0; i++) { printf("\tIP address %d: ", i+1); paddr( (void*) a[i] ); printf("\n"); } }