MFC 获取本机IP、网络ip和物理地址

时间:2024-03-06 08:05:20

获取本机Ip

CString CNet::GetLocalIP()
{
    WSADATA wsaData;
    int err = WSAStartup(MAKEWORD(2, 0), &wsaData);
    if (err != 0)
    {
        return "";
    }

    char szHostName[MAX_PATH] = { 0 };
    int nRetCode;
    nRetCode = gethostname(szHostName, sizeof(szHostName));

    char* lpLocalIP;
    PHOSTENT hostinfo;

    if (nRetCode != 0)
    {
        WSACleanup();
        return "";
    }

    hostinfo = gethostbyname(szHostName);
    lpLocalIP = inet_ntoa(*(struct in_addr*)*hostinfo->h_addr_list);

    WSACleanup();

    return lpLocalIP;
}

获取外网ip:原理是到用百度搜索下本机ip,然后把这个网页下载下来,解析这个文件,找到本机ip。

CString CNet::GetInternetIP()
{
    char buf[2048] = { 0 }; 
    char chURL[1024] = {"https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&rsv_idx=1&tn=baidu&wd=%E6%9C%AC%E6%9C%BAip&rsv_pq=bf583ea000057300&rsv_t=a528kuIZ1osYq0OKQDWPTA3DASK7g6NwL8LPMmrOCGIYzoh8w9D%2FjTTt2tk&rqlang=cn&rsv_enter=1&rsv_sug3=1" };
    CString strPath = "html.tmp";

    URLDownloadToFile(0, chURL, strPath, 0, NULL);

    std::string str_ip("");
    CString strLine;
    CStdioFile file;
    int iCount = 0;
    if (file.Open(strPath, CFile::modeRead))
    {
        while (file.ReadString(strLine))
        {
            iCount++;
            std::string sLine = strLine;
            std::string ascii = UTF_82ASCII(sLine);
            int index = ascii.find("本机IP");
            if (index != -1)
            {
                str_ip = ascii.substr(index + strlen("本机IP") + 1);
                break;
            }
        }
    }
    file.Close();
    CString strIP;
    strIP = str_ip.c_str();
    strIP = strIP.Trim();
    strIP.Replace(" ", "");
    strIP.Replace("</span>", " ");
    return strIP;
}

 

获取mac地址:使用GetAdaptersInfo函数,当然这个函数获取出来的信息也包含本地ip

CString CNet::GetMacAdress()
{
    char MAC[32] = { 0 };
    CString strMac;
    PIP_ADAPTER_INFO pAdapterInfo;
    PIP_ADAPTER_INFO pAdapter = NULL;
    DWORD dwRetVal = 0;
    pAdapterInfo = (IP_ADAPTER_INFO*)malloc(sizeof(IP_ADAPTER_INFO));
    ULONG ulOutBufLen = sizeof(IP_ADAPTER_INFO);

    dwRetVal = GetAdaptersInfo(pAdapterInfo, &ulOutBufLen);

    if (dwRetVal == ERROR_BUFFER_OVERFLOW)
    {
        free(pAdapterInfo);
        pAdapterInfo = (IP_ADAPTER_INFO *)malloc(ulOutBufLen);
        dwRetVal = GetAdaptersInfo(pAdapterInfo, &ulOutBufLen);
    }

    if (dwRetVal == NO_ERROR)
    {
        pAdapter = pAdapterInfo;
        while (pAdapter)
        {
            sprintf_s(MAC, "%02X-%02X-%02X-%02X-%02X-%02X", pAdapter->Address[0], pAdapter->Address[1], pAdapter->Address[2], pAdapter->Address[3], pAdapter->Address[4], pAdapter->Address[5]);
            strMac = MAC;
            pAdapter = pAdapter->Next;
        }
    }
    else
    {
        strMac = "";
    }
    free(pAdapterInfo);
    return strMac;
}
GetAdaptersInfo函数需要引入的头文件和lib文件如下;

#include <IPHlpApi.h>

#pragma comment(lib,"Iphlpapi.lib")