机器是双网卡,网卡驱动一样,而且还不知道本地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);
}