您不必担心,如果它是你正在创建一个AF_INET或AF_INET6插座。 只需将getaddrinfo()调用中的数据传递给socket()调用即可。
例如
/* returns -1 on error, or a connected socket descriptor*/
int opensock(const char *hostname, const char *service)
{
struct addrinfo hint, *host, *res = NULL;
int tcp_sd = -1, error;
memset(&hint, '\0', sizeof(hint));
hint.ai_socktype = SOCK_STREAM;
hint.ai_family = PF_UNSPEC;
error = getaddrinfo(hostname, service, &hint, &res);
if(error){
syslog(LOG_DEBUG,"getaddrinfo failed. Cant find host %s: %m",hostname);
return tcp_sd;
}
for (host = res; host; host = host->ai_next) {
tcp_sd = socket(host->ai_family, host->ai_socktype, host->ai_protocol);
if (tcp_sd < 0) {
continue;
}
if (connect(tcp_sd, host->ai_addr, host->ai_addrlen) < 0) {
close(tcp_sd);
tcp_sd = -1;
continue;
}
break; /* okay we got one */
}
freeaddrinfo(res);
return tcp_sd;
}
来源
2011-03-20 19:44:09
nos
为什么你不能跳过v4地址? – Erik 2011-03-20 17:41:12
@Erik:也许是因为有些主机不支持ipv6 ... – 2011-03-20 17:42:39
@Adrien:我明白OP只需要ip6 ...也许不是。 – Erik 2011-03-20 17:44:39