0 Refrence
http://www.jb51.net/LINUXjishu/77329.html
1 test program
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <netdb.h>
#include <arpa/inet.h>
int main(int argc, char *argv[])
{
int i;
struct hostent * hostp = NULL;
hostp = (struct hostent *)gethostbyname("Nahanni-server");
for(i=0; ; i++) {
if(hostp->h_addr_list[i] != NULL) {
printf("IP:%s\n",inet_ntoa(*(struct in_addr *)hostp->h_addr_list[i]));
}else {
break;
}
}
}
2 /etc/hosts and resulte
/etc/hosts
127.0.0.1 localhost #127.0.1.1 Nahanni-server 192.168.3.8 Nahanni-server # The following lines are desirable for IPv6 capable hosts ::1 ip6-localhost ip6-loopback fe00::0 ip6-localnet ff00::0 ip6-mcastprefix ff02::1 ip6-allnodes ff02::2 ip6-allrouters
resulte
IP:127.0.1.1
IP:192.168.3.8
For example , if you only want to get the 192.168.3.8, you should set the item "127.0.1.1 Nahanni-server" to be ignored , like this
127.0.0.1 localhost
#127.0.1.1 Nahanni-server
192.168.3.8 Nahanni-server
# The following lines are desirable for IPv6 capable hosts
::1 ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters