程序中有一段用于测试网络连通性的代码,其中用到了GetBestInterfaceEx去获得最佳路由接口,其在只开启IPV4或同时开启IPV4与IPV6时都工作正常,即在网络连通时返回true,不通时返回false。但在仅开启IPV6时不能正常工作,在网络连通时GetBestInterfaceEx返回错误码1232L(ERROR_HOST_UNREACHABLE,即主机不可达)。但此时通过ping命令能与远程另一台IPV6的主机通信,也能访问其上架设的网站。
对于这个问题,在网上搜集了一天,未发现相关或类似的问题。请高手指教,先谢谢了。
代码片段如下:
gIphlpapi = LoadLibrary(_T("Iphlpapi.dll"));
if (gIphlpapi != NULL)
{
gGetBestInterfaceEx = (GetBestInterfaceExProc) GetProcAddress(gIphlpapi, "GetBestInterfaceEx");
}
if (gGetBestInterfaceEx == NULL)
{
return false;
}
DWORD res = NO_ERROR;
sockaddr address;
memset(&address, 0, sizeof(sockaddr));
address.sa_family = AF_INET;
res = gGetBestInterfaceEx(&address, &dwIndex);
// Try to get IPv6 interface
if (res != NO_ERROR)
{
// sockaddr can not be used directly to set sa_family to AF_INET6
// Must use sockaddr_in6 structure to get IPv6 route interface
sockaddr_in6 ipv6Address;
memset(&ipv6Address, 0, sizeof(sockaddr_in6));
ipv6Address.sin6_family = AF_INET6;
res = gGetBestInterfaceEx((sockaddr*)&ipv6Address, &dwIndex);
}
return (res == NO_ERROR);