getaddrinfo函数的使用

1.该函数在该函数在 POSIX规范中定义。在linux下要包含头文件 #include<netdb.h>。与getnameinfo是两个功能相反的函数。支持IPv4 和IPv6。

2. 用来表示地址和主机名的结构体为:

struct addrinfo {

int     ai_flags;

    int     ai_family;

    int     ai_socktype;   

int     ai_protocol;

    size_t  ai_addrlen;

struct  sockaddr *ai_addr;

char    *ai_canonname; 

};

3. getaddrinfo():getaddrinfo() 将human-readable text strings representing hostnames or IP addresses 转化为 a dynamically allocated linked list of struct addrinfo structures.

#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
 
int getaddrinfo(const char *hostname,
                const char *service,
                const struct addrinfo *hints,
                struct addrinfo **res);

其中

1).hostname可以是一个域名,如"baidu.com" 或ip地址"127.0.0.1"

2).service 可以是一个端口号;如"80" 或者是服务名如“echo”,也可以为NULL

3).hints可以为NULL,也可以是

4). res 是一个指向addrinfo结构的指针。储存结果。

返回值:0(正确)/非0(错误)


4.freeaddrinfo()

该函数用来释放getaddrinfo()函数申请的内存空间,也即是addrinfo结构的链表。


todo : problem:

调用getaddrinfo函数时:

struct addrinfo *ai;

error = getaddrinfo("www.baidu.com",NULL,NULL,&ai);   //error==0


struct addrinfo *ai;
struct addrinfo addrinfo_hints;
addrinfo_hints.ai_flags = AI_ADDRCONFIG;
addrinfo_hints.ai_family = AF_UNSPEC;
addrinfo_hints.ai_socktype = SOCK_STREAM;
error = getaddrinfo("www.baidu.com",NULL,&addrinfo_hints,&ai);   //error==-7 ?????

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值