一.hostent數據結構是這樣的:
struct hostent {
const char *h_name; // official name of host
char **h_aliases; // alias list
short h_addrtype; // host address type
short h_length; // length of address
char **h_addr_list; // list of addresses from name server
#define h_addr h_addr_list[0] // address, for backward compatiblity
};
typedef uint32_t in_addr_t;
struct in_addr
{
in_addr_t s_addr;
};
這裏是這個數據結構的詳細資料:
struct hostent:
h_name – 地址的正式名稱。
h_aliases – 空字節-地址的預備名稱的指針。
h_addrtype –地址類型; 通常是AF_INET。
h_length – 地址的比特長度。
h_addr_list – 零字節-主機網絡地址指針。網絡字節順序。
h_addr - h_addr_list中的第一地址。
gethostbyname() 成 功時返回一個指向結構體 hostent 的指針,或者 是個空 (NULL) 指針。
這裏是個例子:
#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>
int main(void) {
struct hostent *h;
h = gethostbyname("www.126.com");
if(h==NULL){
herror("gethostbyname");
exit(1);
}
printf("%s\n",h->h_name);
printf("%d\n",h->h_addr);
struct in_addr *in={h->h_addr};
printf("%s\n",inet_ntoa(*in));
// printf("IP Address : %s\n",inet_ntoa(*((struct in_addr *)h->h_addr)));
return EXIT_SUCCESS;
}
在使用 gethostbyname() 的時候,你不能用perror() 打印錯誤信息 (因爲 errno 沒有使用),你應該調用 herror()。
gethostbyname()返回的 struct hostent 數據。
二.in_addr
struct in_addr { in_addr_t s_addr; };
結構體in_addr 用來表示一個32位的IPv4地址.
in_addr_t 一般爲 32位的unsigned long.
其中每8位代表一個IP地址位中的一個數值.
例如192.168.3.144記爲0xc0a80390,其中 c0 爲192 ,a8 爲 168, 03 爲 3 , 90 爲 144
打印的時候可以調用inet_ntoa()函數將其轉換爲char *類型.