日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

gethostbyname()函数说明

發布時間:2024/4/15 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 gethostbyname()函数说明 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

gethostbyname()函數說明——用域名或主機名獲取IP地址

?? ?包含頭文件
??? #include <netdb.h>
??? #include <sys/socket.h>

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

?? ?返回hostent結構體類型指針
??? struct hostent
??? {
??????? char??? *h_name;????????????? ?
??????? char??? **h_aliases;
??????? int???? h_addrtype;
??????? int???? h_length;
??????? char??? **h_addr_list;
??????? #define h_addr h_addr_list[0]
??? };

??? 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。

1 #include <netdb.h>2 #include <sys/socket.h>3 #include <stdio.h>4 5 int main(int argc, char **argv)6 {7 char *ptr, **pptr;8 struct hostent *hptr;9 char str[32]; 10 ptr = argv[1]; 11 12 if((hptr = gethostbyname(ptr)) == NULL) 13 { 14 printf(" gethostbyname error for host:%s\n", ptr); 15 return 0; 16 } 17 18 printf("official hostname:%s\n",hptr->h_name); 19 for(pptr = hptr->h_aliases; *pptr != NULL; pptr++) 20 printf(" alias:%s\n",*pptr); 21 22 switch(hptr->h_addrtype) 23 { 24 case AF_INET: 25 case AF_INET6: 26 pptr=hptr->h_addr_list; 27 for(; *pptr!=NULL; pptr++) 28 printf(" address:%s\n", 29 inet_ntop(hptr->h_addrtype, *pptr, str, sizeof(str))); 30 printf(" first address: %s\n", 31 inet_ntop(hptr->h_addrtype, hptr->h_addr, str, sizeof(str))); 32 break; 33 default: 34 printf("unknown address type\n"); 35 break; 36 } 37 38 return 0; 39 }

  編譯運行
-----------------------------
# gcc test.c
# ./a.out www.baidu.com
official hostname:www.a.shifen.com
alias:www.baidu.com
address:121.14.88.11
address:121.14.89.11
first address: 121.14.88.11

轉載于:https://www.cnblogs.com/sdgwc/p/3225051.html

總結

以上是生活随笔為你收集整理的gethostbyname()函数说明的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。