gethostaddr
封装.c
#include <stdlib.h>
#include <stdio.h>
#include <zconf.h>
#include <netdb.h>
#include <string.h>
#include <zconf.h>
#include <netdb.h>
#define ERROR printf
/**
* 从字符串左边开始将包含给定分隔符在内的右边截断
* @param string {char*} 源字符串
* @param delimiter {int} 分隔符
* @return {char*} 分隔符以右的字符串,当为NULL时表明未找到指定分隔符
*/
char *acl_split_at(char *s, int delimiter){
char *cp;
if ((cp = strchr(s, delimiter)) != 0){
*cp++ = 0;
}
return cp;
}
/**
* 从字符串右边开始将包含给定分隔符在内的右边截断
* @param string {char*} 源字符串
* @param delimiter {int} 分隔符
* @return {char*} 分隔符以右的字符串,当为NULL时表明未找到指定分隔符
*/
char *acl_split_at_right(char *s, int delimiter){
char *cp;
if ((cp = strrchr(s, delimiter)) != 0)
*cp++ = 0;
return cp;
}
static int host_port(char *buf, char **host, char **port){
char *cp = buf;
cp = acl_split_at_right(buf, ':');
*host = buf ;
*port = cp;
return 0;
}
struct addrinfo *acl_host_addrinfo(const char *addr, int type)
{
int err;
struct addrinfo hints, *res0;
char *buf = strdup(addr);
char *host = NULL, *port = NULL;
if (host_port(buf, &host, &port) < 0) {
free(buf);
return NULL;
}
memset(&hints, 0, sizeof(hints));
hints.ai_family = PF_UNSPEC; // (IPv4 and IPv6)
hints.ai_socktype = type; // SOCK_STREAM
hints.ai_flags = AI_V4MAPPED | AI_ADDRCONFIG; // 只有当主机配置了IPv4地址才进行查询IPv4地址;只有当主机配置了IPv6地址才进行查询IPv6地址
// 如果同时指定ai_family为AF_INT6时,如果没有可用的AAAA记录,就i返回A记录对应的IPv4映射的IPV6地址
if ((err = getaddrinfo(host, port, &hints, &res0))) {
ERROR("%s(%d): getaddrinfo error %s, host=%s, addr=%s",
__FILE__, __LINE__, gai_strerror(err), host, addr);
free(buf);
return NULL;
}
free(buf);
return res0;
}
引出.h
struct addrinfo *acl_host_addrinfo(const char *addr, int type)