我不明白爲什麼getaddrinfo
沒有返回一個有效的IPv6地址。getaddrinfo()與IPv6沒有意義
在我的系統下面的代碼打印22:B8:00:00:00:00:00:00:00:00:00:00:00:00
,但我期望的01
的地方,因爲localhost
應該下定決心::1
。
與此同時,sa_data
只有14字節,而IPv6的地址是16個字節,如此看來,最後幾個字節總是砍掉,並且功能不能返回IPv6地址?
有人可以解釋發生了什麼?我該如何在IPv6上使用這個功能?
#include <stdio.h>
#include <WinSock2.h>
#include <WS2TCPIP.h>
#pragma comment(lib, "WS2_32")
int main(int argc, char *argv[])
{
WSADATA wsadata;
WSAStartup(0x0002, &wsadata);
addrinfo addr_hints = { 0, PF_INET6, SOCK_DGRAM, IPPROTO_UDP }, *addrs_out;
getaddrinfo("localhost", "8888", &addr_hints, &addrs_out);
fprintf(stderr,
"%02X:%02X:%02X:%02X:%02X:%02X:%02X:%02X:%02X:%02X:%02X:%02X:%02X:%02X\n",
static_cast<unsigned char>(addrs_out->ai_addr->sa_data[ 0]),
static_cast<unsigned char>(addrs_out->ai_addr->sa_data[ 1]),
static_cast<unsigned char>(addrs_out->ai_addr->sa_data[ 2]),
static_cast<unsigned char>(addrs_out->ai_addr->sa_data[ 3]),
static_cast<unsigned char>(addrs_out->ai_addr->sa_data[ 4]),
static_cast<unsigned char>(addrs_out->ai_addr->sa_data[ 5]),
static_cast<unsigned char>(addrs_out->ai_addr->sa_data[ 6]),
static_cast<unsigned char>(addrs_out->ai_addr->sa_data[ 7]),
static_cast<unsigned char>(addrs_out->ai_addr->sa_data[ 8]),
static_cast<unsigned char>(addrs_out->ai_addr->sa_data[ 9]),
static_cast<unsigned char>(addrs_out->ai_addr->sa_data[10]),
static_cast<unsigned char>(addrs_out->ai_addr->sa_data[11]),
static_cast<unsigned char>(addrs_out->ai_addr->sa_data[12]),
static_cast<unsigned char>(addrs_out->ai_addr->sa_data[13]));
freeaddrinfo(addrs_out);
return 0;
}
首先一定要檢查的getaddrinfo的'的返回值()'。如果它失敗,你的地址將是垃圾。 – Jeff
@Jeff:我在我的實際代碼中;這不是問題。 – Mehrdad