2

我正在尝试使用 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。如何检查我的计算机的地址是什么地址以及其他地址是什么?

4

0 回答 0