inux網路編程--struct hostent結構體__編程

來源:互聯網
上載者:User

轉自:http://blog.csdn.net/yming0221/article/details/7220478

使用這個東西,首先要包含2個標頭檔: #include <netdb.h>
#include <sys/socket.h>

struct hostent *gethostbyname(const char *name);
這個函數的傳入值是網域名稱或者主機名稱,例如" www.google.com.tw","wpc "等等。
傳出值,是一個hostent的結構(如下)。如果函數調用失敗,將返回NULL。
[cpp]  view plain copy print ? struct hostent {   char *h_name;   char **h_aliases;   int h_addrtype;   int h_length;   char **h_addr_list;   };  
解釋一下這個結構:
其中,
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]  view plain copy print ? #include <stdio.h>   #include <stdlib.h>   #include <netdb.h>   #include <sys/socket.h>      int main(int argc, char *argv[])   {           

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.