我正在尝试使用Winsock获取外部IP和MAC地址。在我的电脑上,我安装了VirtualBox。当我试图获取计算机的IP和MAC地址时,我得到2个地址。一个用于计算机,一个用于VirtualBox。这是我获取IP和MAC地址的功能:
long NetUtils::getLocalIpAddress()
{
if( localIpAddress == -1)
{
WSAData wsaData;
if (WSAStartup(MAKEWORD(1, 1), &wsaData) != 0) {
std::cout << "WSAStartup Error " << "WSAGetLastError" <<std::endl;
localIpAddress = -1;
WSACleanup();
return localIpAddress;
}
char ac[80];
if (gethostname(ac, sizeof(ac)) == SOCKET_ERROR) {
std::cout << "Error " << WSAGetLastError() <<" when getting local host name." << std::endl;
localIpAddress = -1;
WSACleanup();
return localIpAddress;
}
struct hostent *phe = gethostbyname(ac);
if (phe == 0) {
std::cout << "Yow! Bad host lookup." << std::endl;
localIpAddress = -1;
WSACleanup();
return localIpAddress;
}
for (int i = 0; phe->h_addr_list[i] != 0; ++i) {
struct in_addr addr;
memcpy(&addr, phe->h_addr_list[i], sizeof(struct in_addr));
std::cout << "Address " << i << ": " << inet_ntoa(addr) << " - " << addr.S_un.S_addr << std::endl;
}
WSACleanup();
return localIpAddress;
}
}
long NetUtils::getLocalMacAddress()
{
IP_ADAPTER_INFO AdapterInfo[16]; // Allocate information
// for up to 16 NICs
DWORD dwBufLen = sizeof(AdapterInfo); // Save memory size of buffer
DWORD dwStatus = GetAdaptersInfo( // Call GetAdapterInfo
AdapterInfo, // [out] buffer to receive data
&dwBufLen); // [in] size of receive data buffer
assert(dwStatus == ERROR_SUCCESS); // Verify return value is
// valid, no buffer overflow
PIP_ADAPTER_INFO pAdapterInfo = AdapterInfo; // Contains pointer to
// current adapter info
do {
PrintMACaddress(pAdapterInfo->Address); // Print MAC address
pAdapterInfo = pAdapterInfo->Next; // Progress through
// linked list
}
while(pAdapterInfo); // Terminate if last adapter
return 0;
}
void NetUtils::PrintMACaddress(unsigned char MACData[])
{
printf("%02X-%02X-%02X-%02X-%02X-%02X\n",
MACData[0], MACData[1], MACData[2], MACData[3], MACData[4], MACData[5]);
}
在我的程序中,我只需要获取计算机的IP和MAC。如何查看我的计算机的地址是什么以及其他地址是什么?