#pragma comment ( lib, "ws2_32.lib" )
#pragma comment ( lib, "Iphlpapi.lib" )
CRITICAL_SECTION cs_out;
/*线程函数*/
void scan_lan(void *p)
{
IPAddr ip_addr;
ULONG mac[2];
ULONG mac_len;
memset (mac, 0xff, sizeof (mac));
mac_len = 6;
ip_addr=inet_addr((char*)p);
DWORD hr = SendARP (ip_addr, 0, mac, &mac_len);
EnterCriticalSection(&cs_out);
if(hr==NO_ERROR) {
unsigned char * mac_addr=(unsigned char*)mac;
printf("\n%s is online\n",p);
printf("mac address is %02X:%02X:%02X:%02X:%02X:%02X\n",
mac_addr[0],mac_addr[1],mac_addr[2],mac_addr[3],mac_addr[4],mac_addr[5]);
}
else {
printf("\n%s is offline\n",p);
}
LeaveCriticalSection(&cs_out);
}
int main(int argc,char * argv[])
{
char ip[256][16];
int i;
HANDLE h_scan[64];
DWORD ID;
if(argc<2) {
printf("Usage: ScanLan ip\n");
return -1;
}
InitializeCriticalSection(&cs_out);
for(i=0;i<=63;i++) {
sprintf(ip[i],"%s.%d",argv[1],i);
if((h_scan[i]=CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)(scan_lan),ip[i],0,&ID))==NULL)
printf("create thread error! ip is %s\n\n",ip[i]);
}
/* MAXIMUM_WAIT_OBJECTS=64*/
WaitForMultipleObjects(64,h_scan,TRUE,-1);
for(i=64;i<=127;i++) {
sprintf(ip[i],"%s.%d",argv[1],i);
if((h_scan[i-64]=CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)(scan_lan),ip[i],0,&ID))==NULL)
printf("create thread error! ip is %s\n\n",ip[i]);
}
WaitForMultipleObjects(64,h_scan,TRUE,-1);
for(i=128;i<=191;i++) {
sprintf(ip[i],"%s.%d",argv[1],i);
if((h_scan[i-128]=CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)(scan_lan),ip[i],0,&ID))==NULL)
printf("create thread error! ip is %s\n\n",ip[i]);
}
WaitForMultipleObjects(64,h_scan,TRUE,-1);
for(i=192;i<=255;i++) {
sprintf(ip[i],"%s.%d",argv[1],i);
if((h_scan[i-192]=CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)(scan_lan),ip[i],0,&ID))==NULL)
printf("create thread error! ip is %s\n\n",ip[i]);
}
WaitForMultipleObjects(64,h_scan,TRUE,-1);
return 0;
}