使用gethostname()函數和gethostbyname()函數獲取主機相關信息

gethostname() : 返回本地主機的標準主機名。

原型如下:

#include <unistd.h>

int gethostname(char *name, size_t len);

參數說明:

這個函數需要兩個參數:

接收緩衝區name,其長度必須爲len字節或是更長,存獲得的主機名。

接收緩衝區name的最大長度

返回值:

如果函數成功,則返回0。如果發生錯誤則返回-1。錯誤號存放在外部變量errno中。

 

gethostbyname()函數說明——用域名或主機名獲取IP地址
    包含頭文件
    #include <netdb.h>
    #include <sys/socket.h>

    函數原型
    struct hostent *gethostbyname(const char *name);
    這個函數的傳入值是域名或者主機名,例如"www.google.cn"等等。傳出值,是一個hostent的結構。如果函數調用失敗,將返回NULL。

    返回hostent結構體類型指針
          

1
2
3
4
5
6
7
8
   struct hostent {
               char  *h_name;            /* official name of host */
               char **h_aliases;         /* alias list */
               int    h_addrtype;        /* host address type */
               int    h_length;          /* length of address */
               char **h_addr_list;       /* list of addresses */
           }
           #define h_addr h_addr_list[0] /* for backward compatibility */

 

    hostent->h_name
    表示的是主機的規範名。例如www.google.com的規範名其實是www.l.google.com。
    
    hostent->h_aliases
    表示的是主機的別名.www.google.com就是google他自己的別名。有的時候,有的主機可能有好幾個別名,這些,其實都是爲了易於用戶記憶而爲自己的網站多取的名字。

    hostent->h_addrtype    
    表示的是主機ip地址的類型,到底是ipv4(AF_INET),還是pv6(AF_INET6)

    hostent->h_length      
    表示的是主機ip地址的長度

    hostent->h_addr_lisst
    表示的是主機的ip地址,注意,這個是以網絡字節序存儲的。千萬不要直接用printf帶%s參數來打這個東西,會有問題的哇。所以到真正需要打印出這個IP的話,需要調用inet_ntop()。

    const char *inet_ntop(int af, const void *src, char *dst, socklen_t cnt) :
    這個函數,是將類型爲af的網絡地址結構src,轉換成主機序的字符串形式,存放在長度爲cnt的字符串中。返回指向dst的一個指針。如果函數調用錯誤,返回值是NULL。

#include <stdio.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
 
void handler(int sig){
        printf("recv a sig=%d\n",sig);
                exit(EXIT_SUCCESS);
}
 
 
#define ERR_EXIT(m) \
        do{ \
                perror(m); \
                exit(EXIT_FAILURE);\
        }while(0);
 
int main(void)
{
        char host[100] = {0};
         if(gethostname(host,sizeof(host)) < 0){
                ERR_EXIT("gethostname");
        }
 
        struct hostent *hp;
        if ((hp=gethostbyname(host)) == NULL){
                ERR_EXIT("gethostbyname");
        }
 
        int i = 0;
        while(hp->h_addr_list[i] != NULL)
        {
                printf("hostname: %s\n",hp->h_name);
                printf("ip: %s\n",inet_ntoa(*(struct in_addr*)hp->h_addr_list[i]));
                i++;
        }
        return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章