int print_socket_info(int sock_fd, struct sockaddr_in *sin, short protocol){
char dbg[INET_ADDRSTRLEN];
char *famstr;
inet_ntop(protocol, &(sin->sin_addr), dbg, INET_ADDRSTRLEN);
printf("============ SOCKET INFORMATION =============\n");
printf("!** socket: %d\n", sock_fd);
printf("!** info->ai_addr: sockaddr_in(\n");
famstr = fam2str(sin->sin_family);
printf("!** sin_family: %s\n", famstr);
printf("!** sin_port: %d\n", ntohs(sin->sin_port));
printf("!** sin_addr: in_addr( s_addr : '%s' )\n", dbg);
printf("!**)\n");
printf("=============================================\n");
return 1;
}
char *fam2str(int fam){
switch (fam){
case AF_INET:
return "AF_INET";
case AF_INET6:
return "AF_INET6";
case AF_UNSPEC:
return "AF_UNSPEC";
default:
return "(UNKNOWN)";
}
return "(UNKNOWN)";
}
如果我像这样传入hint.ai_addr(忽略信息-> ...这是字符串的一部分):
print_socket_info(sock, (struct sockaddr_in *)hint.ai_addr, protocol);
...然后我打印出以下内容...
============ SOCKET INFORMATION =============
!** socket: 3
!** info->ai_addr: sockaddr_in(
!** sin_family: AF_INET6
!** sin_port: 8081
!** sin_addr: in_addr( s_addr : '::1' )
!**)
=============================================
...信息打印正确。接下来我调用函数:
res = getaddrinfo(target_host, target_port, &hint, &info);
到目前为止,我没有收到任何错误。现在,我遍历链表:
struct addrinfo *rp;
for (rp = info; rp != NULL; rp = rp->ai_next){
printf("==> Another element.\n");
print_socket_info(sock, (struct sockaddr_in *) rp->ai_addr, protocol);
}
...我只打印出一个元素:
============ SOCKET INFORMATION =============
!** socket: 3
!** info->ai_addr: sockaddr_in(
!** sin_family: AF_INET6
!** sin_port: 8081
!** sin_addr: in_addr( s_addr : '::' )
!**)
=============================================
...当然,这对 bind() 造成了严重破坏。为什么地址被缩短了?
还有一些奇怪的事情:如果我传入 127.0.0.1 并使用 AF_INET4 ,那么该地址会在整个程序中保持不变(但我只得到一个结果并且绑定仍然失败)。
有任何想法吗?提前致谢。