使用SendARP扫描局域网的计算机


先获得本机IP地址和掩码,得到地址上下限,然后使用SendARP获得MAC地址。缺点是SendARP有超时,导至扫描速度很慢。

// Scaner.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include 
#include 
#include 
#pragma comment(lib, "iphlpapi.lib")
#pragma comment(lib, "ws2_32.lib")
#define IT_TIME 3
int _tmain(int argc, _TCHAR* argv[])
{
	PMIB_IPADDRTABLE IpTable;
	int it = IT_TIME;
	DWORD i;
	int chose;
	ULONG dwSize = 0x1000;
	DWORD RetD;
	while(it-- > 0){
		IpTable = (PMIB_IPADDRTABLE)malloc(dwSize);
		if(!IpTable){
			printf("内存不足\n");
			goto End;
		}
		//注意得到的是网络字节序,即ip的msb在底地址
		RetD = GetIpAddrTable(IpTable, &dwSize, FALSE);
		if(RetD == NO_ERROR)
			break;
		else if(RetD == ERROR_INSUFFICIENT_BUFFER){
			free(IpTable);
		}else{
			free(IpTable);
			printf("发生未知错误\n");
			goto End;
		}
	}
	for(i = 0; i < IpTable->dwNumEntries; i++){
		printf("    %d: %s\n", i, inet_ntoa(*(in_addr*)&(IpTable->table[i].dwAddr)));
	}
	printf("选择网络(0):");
	chose = -1;
	scanf("%d", &chose);
	if(chose == -1 || chose >= IpTable->dwNumEntries)
		chose = 0;
	DWORD LowAddr;
	DWORD HighAddr;
	LowAddr = ntohl((IpTable->table[chose].dwAddr & IpTable->table[chose].dwMask)) + 1;
	HighAddr = ntohl(IpTable->table[chose].dwAddr | ~IpTable->table[chose].dwMask) - 1;
	unsigned char mac[6];
	int size = 0;
	in_addr in;
	for(i = LowAddr; i <= HighAddr; i++){
		dwSize = 6;
		RetD = SendARP(ntohl(i), IpTable->table[chose].dwAddr, mac, &dwSize);
		if(RetD == NO_ERROR){
			in.S_un.S_addr = ntohl(i);
			printf("%s, mac is ", inet_ntoa(in));
			for(int j = 0; j < 5; j++){
				printf("%02x:", mac[j]);
			}
			printf("%02x\n", mac[5]);
		}
	}
End:

	return 0;
}


你可能感兴趣的:(使用SendARP扫描局域网的计算机)