/etc/hosts configure

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


It seems that the function gethostbyname() get the host ip according the file /etc/hosts, so you must be careful to get the ip that you supposed.

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



發佈了52 篇原創文章 · 獲贊 1 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章