表頭文件: #include<netdb.h>
struct addrinfo
{
int ai_flags;
int ai_family; //AF_INET,AF_INET6,UNIX etc
int ai_socktype; //STREAM,DATAGRAM,RAW
int ai_protocol; //IPPROTO_IP, IPPROTO_IPV4, IPPROTO_IPV6 etc
size_t ai_addrlen;//length of ai_addr
char* ai_canonname; //full hostname
struct sockaddr* ai_addr; //addr of host
struct addrinfo* ai_next;
}
value of ai_falgs:
AI_PASSIVE: Socket address is intended for `bind'.
AI_CANONNAME:Request for canonical name.
AI_NUMERICHOST: Don't use name resolution.
AI_V4MAPPED: IPv4 mapped addresses are acceptable.
AI_ALL: Return IPv4 mapped and IPv6 addresses.
AI_ADDRCONFIG:Use configuration of this host to choose
定義函數:
int getaddrinfo( const char *hostname, const char *service, const struct addrinfo *hints,
struct addrinfo **result );
函數說明:
getaddrinfo函數能夠處理名字到地址以及服務到端口這兩種轉換,返回的是一個sockaddr 結構的鏈而 不是一個地址清單。它具有協議無關性。
hostname:一個主機名或者地址串(IPv4的點分十進制串或者IPv6的16進制串)
service:一個服務名或者10進制端口號數串。
hints:可以是一個空指針,也可以是一個指向某個addrinfo結構的指針,調用者在這個結構中填入關於期望返回的信息類型的暗示。舉例來說:如果指定的服務既支持TCP也支持UDP,那麼調用者可以把hints結構中的ai_socktype成員設置成SOCK_DGRAM使得返回的僅僅是適用於數據報套接口的信息。返回0: 成功,返回非0: 出錯。
定義函數:const char *gai_strerror( int error );
函數說明:
該函數以getaddrinfo返回的非0錯誤值的名字和含義為他的唯一參數,返回一個指向對應的出錯信息串的指針。
定義函數: void freeaddrinfo( struct addrinfo *ai );
函數說明:
由getaddrinfo返回的所有存儲空間都是動態獲取的,這些存儲空間必須通過調用freeaddrinfo返回給系統。
例子:
[cpp]
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
int
lookup_host (const char *host)
{
struct addrinfo hints, *res;
int errcode;
char addrstr[100];
void *ptr;
memset (&hints, 0, sizeof (hints));
hints.ai_family = PF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags |= AI_CANONNAME;
errcode = getaddrinfo (host, NULL, &hints, &res);
if (errcode != 0)
{
perror ("getaddrinfo");
return -1;
}
printf ("Host: %s\n", host);
while (res)
{
inet_ntop (res->ai_family, res->ai_addr->sa_data, addrstr, 100);
switch (res->ai_family)
{
case AF_INET:
ptr = &((struct sockaddr_in *) res->ai_addr)->sin_addr;
break;
case AF_INET6:
ptr = &((struct sockaddr_in6 *) res->ai_addr)->sin6_addr;
break;
}
inet_ntop (res->ai_family, ptr, addrstr, 100);
printf ("IPv%d address: %s (%s)\n", res->ai_family == PF_INET6 ? 6 : 4,
addrstr, res->ai_canonname);
res = res->ai_next;
}
return 0;
}
int
main (int argc, char *argv[])
{
if (argc < 2)
exit (1);
return lookup_host (argv[1]);
}
作者:wallwind