windows下根据网卡名获取MAC地址

 

机器是双网卡,网卡驱动一样,而且还不知道本地IP地址,所以之前根据GetAdaptersInfo方法行不通。

static int getFileContent(const string& file,string& data)
{
    ifstream Osread(file);
    if (Osread.fail())
    {
        cout << "error open file " << file << endl;
        return -1;
    }
    string line = "";
    while (getline(Osread, line))
    {
        data += line;
        data += "\n";
    }

    Osread.close();
    return 0;
}

int getMacByCmd(const string& adapterName,string& macAddr)
{
    char cmd[] = "ipconfig/all > ipInfo.dat"; //获取MAC命令行    
    const string strEnSearch = "Physical Address. . . . . . . . . : "; //网卡MAC地址的前导信息
    const string strChSearch = "物理地址. . . . . . . . . . . . . : ";


    string            strBuffer;
    long            ipos = 0;
    int ret = -1;

    if (0 == system(cmd))
    {
        if (0 == getFileContent("ipInfo.dat", strBuffer))
        {
            //cout << strBuffer << endl;

            ipos = strBuffer.find(adapterName);

            if (ipos != string::npos)//区分中英文的系统
            {
                strBuffer = strBuffer.substr(ipos);
                ipos = strBuffer.find(strChSearch);
                if (ipos==string::npos)
                {
                    ipos = strBuffer.find(strEnSearch);
                }
                //提取MAC地址串
                if (ipos != string::npos)
                {
                    strBuffer = strBuffer.substr(ipos + strChSearch.length());
                    ipos = strBuffer.find("\n");
                    strBuffer = strBuffer.substr(0, ipos);
                    
                    //trim字符串
                    strBuffer.erase(0, strBuffer.find_first_not_of(" "));
                    strBuffer.erase(strBuffer.find_last_not_of(" ") + 1);


                    //去掉中间的“00-50-EB-0F-27-82”中间的'-'为':'
                    int j = 0;
                    for (int i = 0; i                     {
                        if (strBuffer[i] == '-')
                        {
                            strBuffer[i] = ':';
                        }
                    }
                    macAddr = strBuffer;
                    system("del ipInfo.dat");
                    ret = 0;
                }                
            }
        }
    }

    return(ret);
}


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部