我們在網路程式設計中有時可能會用MAC地址,如果我們用VC++的話可以用UCHAR Netbios(
PNCB pncb /* pointer to the network control block*/)擷取;但是我在實際的應用過程中發現它並不是每次都管用的.在一個有無線網卡的筆記本上,我一個裝有虛擬機器的筆記本上都現我了擷取不到MAC的情況,也許我對這個函數的用法沒有深入瞭解吧!
我借用了JAVA程式在通用的一種擷取MAC的方法,借用IPCONFIG來獲得所有網卡的資訊。下面我們就來看一下具體方法。
首先我們定義一個結構用於儲存網卡資訊:
typedef struct _tagAdapterInfo{
CString Description;//網卡描述
CString PhysicalAddr;//MAC
CString IpAddr[64];//IP地址最多64個
CString SubnetMask[64];//每個IP對的掩碼最多64個
CString Gateway;//預設閘道
LONG lIpNum;//網卡對應的IP數
}AdapterInfo,*PAdapterInfo;
我們定義一個獲得本機所有網卡資訊的方法:
int GetAllAdapterInfo(CArray<AdapterInfo,AdapterInfo>& AdapterInfoList,
CString& Error);
下面讓我們來看一下實現:
int CTestDlg::GetAllAdapterInfo(
CArray<AdapterInfo,AdapterInfo>& AdapterInfoList,CString Error)
{
HANDLE hRead,hWrite;//定義輸入輸出控制代碼
CString strError;//錯誤資訊
CString strCon,strBuf;
BOOL nReturn;
char buffer[2048]={0};
LPSTR p="ipconfig /all";
unsigned long lnReadNum;
int nIndex=0,from=0,to=0,nLoop=0;
STARTUPINFO sa;
PROCESS_INFORMATION pinfo;
SECURITY_ATTRIBUTES saPipe;
saPipe.nLength= sizeof( SECURITY_ATTRIBUTES );
saPipe.lpSecurityDescriptor = NULL;
saPipe.bInheritHandle = TRUE;
if (!CreatePipe(&hRead,&hWrite,&saPipe,0))//建立管道
{
strError.Format("CREATE PIPE ERRORCODE:%d",GetLastError());
Error=strError;
return 1;
}
memset( &sa, 0, sizeof(sa));
sa.cb=sizeof(sa);
sa.dwFlags=STARTF_USESHOWWINDOW |STARTF_USESTDHANDLES;
sa.wShowWindow = SW_HIDE;
sa.hStdOutput=hWrite;
sa.hStdError=hWrite;
//建立進程
nReturn=::CreateProcess(NULL,p,&saPipe,&saPipe,
TRUE,0,NULL,NULL,&sa,&pinfo);
if (!nReturn)
{
strError.Format("CREATE PROCESS ERRORCODE:%d",GetLastError());
Error=strError;
return 2;
}
//Sleep(1000);
CloseHandle( pinfo.hThread );
CloseHandle( pinfo.hProcess );
CloseHandle( hWrite);
//讀即管道的輸出
do{
memset(buffer,0,2048);
nReturn=ReadFile(hRead,buffer,MAX_PATH,&lnReadNum,NULL);
if (nReturn)
{
strBuf.Format("%s",buffer);
strCon+=strBuf;
}
}while(nReturn&&lnReadNum);
AdapterInfo info;
//輸出資訊裡尋找網卡資訊
do
{
nIndex=strCon.Find("Description",nIndex);
if (nIndex<=-1)
{
break;
}
from=strCon.Find(":",nIndex)+2;
to=strCon.Find("/n",from);
info.Description=strCon.Mid(from,to-from-1);
nIndex=to;
nIndex=strCon.Find("Physical Address",nIndex);
from=strCon.Find(":",nIndex)+2;
to=strCon.Find("/n",from);
info.PhysicalAddr=strCon.Mid(from,to-from-1);
nIndex=to;
nLoop=0;
while(nLoop<64)
{
nIndex=strCon.Find("IP Address",nIndex);
if (nIndex<=-1)
{
break;
}
from=strCon.Find(":",nIndex)+2;
to=strCon.Find("/n",from);
info.IpAddr[nLoop]=strCon.Mid(from,to-from-1);
nIndex=to;
nIndex=strCon.Find("Subnet Mask",nIndex);
from=strCon.Find(":",nIndex)+2;
to=strCon.Find("/n",from);
info.SubnetMask[nLoop]=strCon.Mid(from,to-from-1);
nLoop++;
}
info.lIpNum=nLoop;
nIndex=to;
nIndex=strCon.Find("Default Gateway",nIndex);
from=strCon.Find(":",nIndex)+2;
to=strCon.Find("/n",from);
info.Gateway=strCon.Mid(from,to-from-1);
AdapterInfoList.Add(info);
}while(TRUE);
return 0;
}
方法只是管道的一種最基本的應用,拿來與大家分享一下!另外我們還可以用IP協助函數來獲得IP