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<strBuffer.length(); i++)
                    {
                        if (strBuffer[i] == '-')
                        {
                            strBuffer[i] = ':';
                        }
                    }
                    macAddr = strBuffer;
                    system("del ipInfo.dat");
                    ret = 0;
                }                
            }
        }
    }

    return(ret);
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值