Friday, October 9, 2009

gethostbyname() simple example code

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

int main()
{
struct hostent *host;
host = gethostbyname("localhost");
char **alias;
alias = host->h_aliases;
while(*alias != NULL)
{
printf("%s\n",*alias);
alias++;
}
switch(host->h_addrtype)
{
case AF_INET:
printf("IP ver 4 \n");
break;
case AF_INET6:
printf("IP ver 6 \n");
break;
}
char buff[INET_ADDRSTRLEN];
sockaddr_in addr;
addr.sin_addr = *(struct in_addr *)host->h_addr_list[0];
addr.sin_family = host->h_addrtype;
inet_ntop(AF_INET,&(addr.sin_addr.s_addr),buff,sizeof(buff));
printf("%s\n",buff);
return 0;
}

No comments:

Post a Comment