The Hostent Structure
/********************** Code below shows that on some ********************/
/********************** machines the array of address ********************/
/********************** pointers is a struct in_addr ********************/
/********************** on some architectures like SGI.********************/
#define MAXBUF 256 /***** Demo of Important Functions *****/
#include <sys/types.h>
#include <sys/socket.h> /* for AF_INET constant */
#include <netdb.h> /* for struct hostent */
#include <netinet/in.h> /* For struct in_addr */
#include <arpa/inet.h> /* for inet_ntoa() */
#include <stdio.h>
/* struct in_addr{ unsigned long s_addr}; */
main()
{
struct hostent *hptr;
char **ch_ptr, buf[100];
struct in_addr **inaddr_ptr;
struct sockaddr_in server;
int active;
hptr = gethostbyname("columbia.atc.fhda.edu"); /* Get a hostent structure
from challenger */
printf("h_name component is %s\n", hptr->h_name);
ch_ptr = hptr->h_aliases;
while (*ch_ptr)
{
printf("h_aliases list: %s\n", *ch_ptr);
ch_ptr++;
}
inaddr_ptr = (struct in_addr **) hptr->h_addr_list;
while (*inaddr_ptr != NULL)
{
printf("h_addr_list raw: %lu\n", (*inaddr_ptr)->s_addr);
printf("h_addr_list: %s\n", inet_ntoa(**inaddr_ptr));
inaddr_ptr++;
}
memset(&server, 0, sizeof(struct sockaddr_in));
server.sin_family = AF_INET;
server.sin_port = htons(13); /**** Daytime server port number ****/
/********* IPv4 Conversion Functions ***********/
server.sin_addr.s_addr = inet_addr("153.18.200.6"); /**** Deprecated! ****/
printf("raw address is: %lu\n", server.sin_addr.s_addr);
inet_aton("153.18.200.6", &server.sin_addr);
printf("raw address is: %lu\n", server.sin_addr.s_addr);
if ((active = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
perror("Socket");
exit(1);
}
if (connect(active, (struct sockaddr *) &server, sizeof(server)) < 0)
{
perror("Connect");
exit(2);
}
write(active, "Hello", 5);
memset(buf, 0, 10);
read(active, buf, 100);
printf("Received \"%s\" from server.\n", buf);
}
/************************** Program Output Below ***************************/
h_name component is columbia.atc.fhda.edu
h_addr_list raw: 2568144904
h_addr_list: 153.18.200.8
raw address is: 2568144902
raw address is: 2568144902
Received "Wed Apr 12 14:58:40 2000
" from server.