我编写了一个应用程序,它使用运行的Windows PC的IP地址填充组合框。除一台VMWare VM外,它可以正常工作。我无法访问VM,但被告知已针对特定IP地址进行了配置,并且所有者已将其更改为动态获取。以下是他遵循的步骤:
VM上的IPConfig报告自动分配的IP地址。我的代码返回先前硬编码的IP。我使用我的代码,使用getaddrinfo和使用gethostbyname的替代方法创建了一个控制台测试应用程序。 gethostbyname代码返回新的IP,匹配IPConfig。
这是getaddrinfo代码:
// the current method
void GetAI()
{
std::cout << "*** getaddrinfo ***\n";
struct addrinfo hints;
memset(&hints, 0, sizeof(addrinfo));
hints.ai_family = AF_INET; // IPv4 only
hints.ai_socktype = SOCK_STREAM; // TCP socket only
hints.ai_protocol = IPPROTO_TCP; // TCP protocol only
hints.ai_flags = AI_PASSIVE; // intend to bind
char szPath[128] = "";
gethostname(szPath, sizeof(szPath));
std::cout << "Host name is " << szPath << "." << std::endl;
char* asciiPort = "";
struct addrinfo* result;
if (getaddrinfo(szPath, asciiPort, &hints, &result))
{
std::cout << "getaddrinfo call failed\n";
return;
}
struct addrinfo* rp;
int i(0);
for (rp = result; rp != NULL; rp = rp->ai_next)
{
const int BIGENOUGH = 46;
WCHAR ipstringbuffer[BIGENOUGH];
memset(ipstringbuffer, 0, BIGENOUGH);
struct sockaddr_in* sockaddr_ipv4 = (struct sockaddr_in*) rp->ai_addr;
std::cout << "Address " << i++ << ": " << inet_ntoa(sockaddr_ipv4->sin_addr) << std::endl;
}
}
gethostbyname代码:
// the deprecated method
int GetHBN()
{
std::cout << "*** gethostbyname ***\n";
char ac[80];
if (gethostname(ac, sizeof(ac)) == SOCKET_ERROR)
{
std::cerr << "Error " << WSAGetLastError() <<
" when getting local host name." << std::endl;
return 1;
}
std::cout << "Host name is " << ac << "." << std::endl;
hostent *phe = gethostbyname(ac);
if (phe == 0)
{
std::cerr << "Bad host lookup." << std::endl;
return 1;
}
for (int i = 0; phe->h_addr_list[i] != 0; ++i)
{
in_addr addr;
memcpy(&addr, phe->h_addr_list[i], sizeof(in_addr));
std::cout << "Address " << i << ": " << inet_ntoa(addr) << std::endl;
}
return 0;
}