主机名、服务与地址的映射——getaddrinfo(),getnameinfo(),gai_strerror()


/* Structure to contain information about address of a service provider.  */
struct addrinfo
{
  int ai_flags;			/* Input flags.  */
  int ai_family;		/* Protocol family for socket.  */
  int ai_socktype;		/* Socket type.  */
  int ai_protocol;		/* Protocol for socket.  */
  socklen_t ai_addrlen;		/* Length of socket address.  */
  struct sockaddr *ai_addr;	/* Socket address for socket.  */
  char *ai_canonname;		/* Canonical name for service location.  */
  struct addrinfo *ai_next;	/* Pointer to next in list.  */
};

getaddrinfo()

The getaddrinfo function allows us to map a host name and a service name to an address.(APUE-2e)

int getaddrinfo(const char *node, const char *service, const struct addrinfo *hints, struct addrinfo **res);
void freeaddrinfo(struct addrinfo *res);
const char *gai_strerror(int errcode);

"hints" 并不是缩写,就是英文愿意“线索,提示”的意思


Note:

(1) getaddrinfo() sets res to point to a dynamically-allocated linked list of  addrinfo  structures, linked by the ai_next member.   There are several reasons why the linked list may have more than one addrinfo structure, including:  if  the  network host is multi-homed; or if the same service is available from multiple socket  protocols  (one SOCK_STREAM address and another SOCK_DGRAM address, for example).

(2) If getaddrinfo fails, we can't use perror or strerror to generate an error message. Instead, we need to callgai_strerrorto convert the error code returned into an error message.

下面的 getnameinfo 也用 gai_strerror 收集错误信息。

(3) 注意addrinfo.ai_flags AI_*的含义(见例子)

(4) getaddri

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值