您的位置:首页 > 其它

getaddrinfo简单应用——取得IP地址

2015-12-15 13:52 288 查看
转自:http://biancheng.dnbcw.info/linux/265956.html

一个域名可能对应好几个ip地址

./a.out www.baidu.com

115.239.210.27

115.239.211.112

getaddrinfo提供独立于协议的名称解析

函数原型:
#include <sys/types.h>

#include <sys/socket.h>

#include <netdb.h>

int getaddrinfo(const char *node, const char *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(struct addrinfo));

hints.ai_family = AF_INET; /* Allow IPv4 */

hints.ai_flags = AI_PASSIVE; /* For wildcard IP address */

hints.ai_protocol = 0; /* Any protocol */

hints.ai_socktype = SOCK_STREAM;

ret = getaddrinfo(argv[1], NULL,&hints,&res);

if (ret == -1) {

perror("getaddrinfo");

exit(1);

}

for (cur = res; cur != NULL; cur = cur->ai_next) {

addr = (struct sockaddr_in *)cur->ai_addr;

printf("%s\n", inet_ntop(AF_INET,

&addr->sin_addr, ipbuf, 16));

}

freeaddrinfo(res);

exit(0);

}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: