CString ipTools::IPToMAC( CStringIpAddStr )
{
BYTEbyMAC[6];
ZeroMemory(byMAC,6);
DWORDdwLen = 6;
intiReturn = SendARP( IPStrToNaddress(IpAddStr), 0, (PULONG) &byMAC,&dwLen);
if( iReturn == NO_ERROR)
{
CStringtmp;
tmp.Format(_T("%.2X-%.2X-%.2X-%.2X-%.2X-%.2X"),
byMAC[0],
byMAC[1],
byMAC[2],
byMAC[3],
byMAC[4],
byMAC[5]);
returntmp;
}
else
{
return_T("00-00-00-00-00-00");
}
}
对于活动IP 就可以通过IP 获取其机器名,WinSocket中提供了一个函数getnameinfo 可以根据IP 返回机器名,但是这个函数执行非常慢,正常情况下调用这个函数取机器名,返回需要 1 -2 秒(是秒哦不是毫秒啊)这种效率是难以接受的,因而我们可以更一种方案人为构建一个NetBiosNs 的数据包,发向目标IP ,NETBIOS协议是由IBM公司开发,该协议是一种在局域网上的程序可以使用的应用程序编程接口,为程序提供了请求低级服务的统一的命令集,作用是为了给局域网提供网络以及其他特殊功能。系统可以利用WINS服务、广播及Lmhost文件等多种模式将NetBIOS名(特指基于NETBIOS协议获得计算机名称)解析为相应IP地址,实现信息通讯。
void ipTools::InitNetBiosNs(TNetBiosNS*nbns)
{
nbns->tID=0x0000;
nbns->Flags=0x1000;
nbns->Questions=0x0100;
nbns->AnswerRRs=0x0000;
nbns->AuthorityRRs=0x0000;
nbns->AdditionalRRs=0x0000;
nbns->Name[0]=0x20;
nbns->Name[1]=0x43;
nbns->Name[2]=0x4b;
for(inti=3;i<33;i++)
nbns->Name[i]=0x41;
nbns->Name[33]=0x00;
nbns->tType=0x2100;
nbns->tClass=0x0100;
}
CString ipTools::IPGetPCName( CStringipAddStr )
{
//获取远程机器名
WSADatawsadata;
WSAStartup(MAKEWORD(2,2),&wsadata);
SOCKETudpClient = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
sockaddr_inSrvAddr;
USES_CONVERSION;
SrvAddr.sin_addr.S_un.S_addr= inet_addr(T2A(ipAddStr));// IpStrToNadd(ipAddStr);//inet_addr((LPSTR)(LPCTSTR)ipAddStr);
SrvAddr.sin_family=AF_INET;
SrvAddr.sin_port=htons(137);
//if(connect(udpClient,(SOCKADDR*)&SrvAddr,sizeof(SOCKADDR))== SOCKET_ERROR)
// goto err;
TNetBiosNSnbns;
InitNetBiosNs(&nbns);
if(sendto(udpClient,(char*)&nbns,sizeof(nbns),0,(SOCKADDR*)&SrvAddr,sizeof(SOCKADDR))== SOCKET_ERROR)
gotoerr;
charrecvBuf[512];
ZeroMemory(recvBuf,512);
intlen = sizeof(SOCKADDR);
if(recvfrom(udpClient,recvBuf,512,0,(SOCKADDR*)&SrvAddr,&len)== SOCKET_ERROR)
gotoerr;
closesocket(udpClient);
WSACleanup();
for(inti=57;i<57+18;i++)
if(recvBuf[i]<0x20)
recvBuf[i]=0;
return(CString)&recvBuf[57];
err:
CStringErrorCode;
ErrorCode.Format(_T("%d"),GetLastError());
return_T("Error: " + ErrorCode );
}
voidCMFCApplication1Dlg::OnBnClickedButton1()
{
//TODO: 在此添加控件通知处理程序代码
ipToolstest;
inti = test.IP2Count(_T("192.168.50.1"),_T("192.168.50.254"));
CString sIP = _T("192.168.50.1");
for(int j=0;jIpStr = sIP;
CloseHandle(CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)AddList,(LPVOID)AddIP,0,0));
sIP = test.NextIPaddress( sIP );
}
DWORD WINAPI AddList( LPVOID ip )
{
ipTools test;
//CString tmp = *(CString*)ip;
AddIPRecord* AddIP = (AddIPRecord*)ip;
CString host =_T("");
//AfxMessageBox( AddIP->IpStr);
CString mac = test.IPToMAC( AddIP->IpStr );
host = test.IPGetPCName( AddIP->IpStr );
if( mac !=_T("00-00-00-00-00-00") )
{
((CMFCApplication1Dlg*)AfxGetApp()->m_pMainWnd)->ListBox1.AddString(AddIP->IpStr +_T("::") +mac +_T("::") +host );
}
delete AddIP;
return 0;
}