转自:http://blog.chinaunix.net/uid-24567872-id-87645.html
getaddrinfo
提供独立于协议的名称解析
函数原型:
#include<sys/types.h> #include<sys/socket.h> #include<netdb.h>
int getaddrinfo(constchar*node,constchar *service, const struct addrinfo *hints, struct addrinfo **res);
|
函数描述:
Given node and service, which identify an Internet host and a service,
getaddrinfo() returns one or more addrinfo structures, each of which
contains an Internet address that can be specified in a call to bind(2)
or connect(2). The getaddrinfo() function combines the functionality
provided by the getservbyname(3) and getservbyport(3) functions into a
single interface, but unlike the latter functions, getaddrinfo() is
reentrant and allows programs to eliminate IPv4-versus-IPv6 dependen‐
cies.
参数node:指向一个
主机名(域名)或者
地址串(IPv4的点分十进制串或者IPv6的16进制串)。
参数service:指向一个
服务名或者10进制
端口号数串。
node,service不能同时为NULL。
参数hints,它可以是一个空指针,也可以是一个指向某个addrinfo结构的指针,调用者在这个结构中填入关于期望返回的信息类型的线索。
struct addrinfo {
int ai_flags;
int ai_family;//AF_INET,AF_INET6或者AF_UNSPEC
int ai_socktype;//SOCK_STREAM or SOCK_DGRAM
int ai_protocol;//0
size_t ai_addrlen;//往下参数在hints中均为0或NULL
struct sockaddr *ai_addr;
char *ai_canonname;
struct addrinfo *ai_next;
};
如果本函数返回成功,那么由res参数指向的变量已被填入一个指针,它指向的是由其中的ai_next成员串联起来的addrinfo结构链表。可以导致返回多个addrinfo结构的情形有以下2个:
1.如果与node参数关联的地址有多个,那么适用于所请求地址簇的每个地址都返回一个对应的结构。
2.如果service参数指定的服务支持多个套接口类型,那么每个套接口类型都可能返回一个对应的结构,具体取决于hints结构的ai_socktype成员。
实例:输入网址,输出IP地址
#include<sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <arpa/inet.h>
int main(int argc,char**argv) { if (argc != 2) { printf("Usag...\n"); exit(1); } struct addrinfo hints; struct addrinfo*res,*cur; int ret; struct sockaddr_in*addr; char ipbuf[16];
memset(&hints, 0,sizeof(structaddrinfo)); hints.ai_family = AF_INET; /* Allow IPv4 */ hints.ai_flags = AI_PASSIVE; /* For wildcard IP address */ hints.ai_protocol = IPPROTO_IP;/* Any protocol */ hints.ai_socktype = SOCK_STREAM; ret = getaddrinfo(argv[1],NULL,&hints,&res); if (ret != 0){ perror("getaddrinfo"); exit(1); } for (cur = res; cur !=NULL; cur= cur->ai_next){ addr = (structsockaddr_in*)cur->ai_addr; printf("%s\n", inet_ntop(AF_INET, &addr->sin_addr, ipbuf, 16)); } freeaddrinfo(res); exit(0); } |
在设备上测试的时候经常出现无法解析域名的情况,后来看了下设备的DNS设置的是8.8.8.8(谷歌免费DNS服务器IP),改用公司使用的DNS之后基本再没出现过域名无法解析的情况了。原因的话,大家可以去百度8.8.8.8