歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux管理 >> Linux網絡 >> Linux網絡編程--struct hostent結構體

Linux網絡編程--struct hostent結構體

日期:2017/3/1 10:35:48   编辑:Linux網絡

使用這個東西,首先要包含2個頭文件:

#include <netdb.h>
#include <sys/socket.h>

struct hostent *gethostbyname(const char *name);
這個函數的傳入值是域名或者主機名,例如" www.google.com.tw","wpc "等等。
傳出值,是一個hostent的結構(如下)。如果函數調用失敗,將返回NULL。
[cpp]
  1. struct hostent {
  2. char *h_name;
  3. char **h_aliases;
  4. int h_addrtype;
  5. int h_length;
  6. char **h_addr_list;
  7. };
解釋一下這個結構:
其中,
char *h_name 表示的是主機的規范名。例如 www.google.com 的規范名其實是 www.l.google.com 。
char **h_aliases 表示的是主機的別名。 www.google.com 就是google他自己的別名。有的時候,有的主機可能有好幾個別名,這些,其實都是為了易於用戶記憶而為自己的網站多取的名字。
int h_addrtype 表示的是主機ip地址的類型,到底是ipv4(AF_INET),還是ipv6(AF_INET6)
int h_length 表示的是主機ip地址的長度
int **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。

下面的例子

[cpp]

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <netdb.h>
  4. #include <sys/socket.h>
  5. int main(int argc, char *argv[])
  6. {
  7. struct hostent *h;
  8. if (argc != 2) { /* 檢查命令行 */
  9. fprintf(stderr,"usage: getip address\n");
  10. exit(1);
  11. }
  12. if ((h=gethostbyname(argv[1])) == NULL) { /* 取得地址信息 */
  13. error("gethostbyname");
  14. exit(1);
  15. }
  16. printf("Host name : %s\n", h->h_name);
  17. printf("IP Address : %s\n",inet_ntoa(*((struct in_addr *)h->h_addr)));
  18. return 0;
  19. }
運行結果如下

Copyright © Linux教程網 All Rights Reserved