学习:
1、对于IP的转换
2、MAC地址的转换
IN_ADDR结构:表示IPv4地址
typedef struct in_addr {
union {
struct {
UCHAR s_b1;
UCHAR s_b2;
UCHAR s_b3;
UCHAR s_b4;
} S_un_b;
struct {
USHORT s_w1;
USHORT s_w2;
} S_un_w;
ULONG S_addr;
} S_un;
} IN_ADDR, *PIN_ADDR, *LPIN_ADDR;
SendARP:发送一个地址解析协议(ARP)请求,以获取该物理地址对应于指定的目标IPv4地址
IPHLPAPI_DLL_LINKAGE DWORD SendARP(
IPAddr DestIP,
IPAddr SrcIP,
PVOID pMacAddr,
PULONG PhyAddrLen
);
单线程扫描实现代码:
#include<Windows.h>
#include <iphlpapi.h>
#include<stdio.h>
#pragma comment(lib,"ws2_32.lib")
#pragma comment(lib,"iphlpapi.lib")
bool WINAPI arpScan(in_addr mAddr) {
ULONG MacArr[2];
DWORD AddrLen = 6;
if (SendARP(mAddr.S_un.S_addr, NULL, MacArr, &AddrLen) == NO_ERROR) {
printf("存活IP:%s MAC:", inet_ntoa(mAddr));
BYTE *bPhysAddr = (BYTE *) MacArr;
for (int i = 0; i < (int)AddrLen; i++) {
if (i == (AddrLen - 1))
printf("%.2X
", (int)bPhysAddr[i]);
else
printf("%.2X-", (int)bPhysAddr[i]);
}
return true;
}
return false;
}
int main(int argc, char * argv[]) {
in_addr mAddr;
char ipStart[] = "192.168.1.104";
mAddr.S_un.S_addr = inet_addr(ipStart)
arpScan(mAddr);
return 0;
}
多线程实现的代码: 这里保证线程安全用的是线程锁
#include<Windows.h>
#include <iphlpapi.h>
#include<stdio.h>
#pragma comment(lib,"ws2_32.lib")
#pragma comment(lib,"iphlpapi.lib")
CRITICAL_SECTION myLock;
bool WINAPI arpScan(in_addr mAddr);
DWORD WINAPI ThreadProc(LPVOID lpParameter) {
in_addr addr;
addr.S_un.S_addr = (ULONG)lpParameter;
arpScan(addr);
return 0;
}
bool WINAPI arpScan(in_addr mAddr) {
ULONG MacArr[2];
DWORD AddrLen = 6;
EnterCriticalSection(&myLock);
if (SendARP(mAddr.S_un.S_addr, NULL, MacArr, &AddrLen) == NO_ERROR) {
printf("存活IP:%s MAC:", inet_ntoa(mAddr));
BYTE *bPhysAddr = (BYTE *) MacArr;
for (int i = 0; i < (int)AddrLen; i++) {
if (i == (AddrLen - 1))
printf("%.2X
", (int)bPhysAddr[i]);
else
printf("%.2X-", (int)bPhysAddr[i]);
}
LeaveCriticalSection(&myLock);
return true;
}
return false;
}
int main(int argc, char * argv[]) {
InitializeCriticalSection(&myLock);
in_addr mAddrStart;
in_addr mAddrEnd;
mAddrStart.S_un.S_addr = inet_addr("192.168.1.1"); //inet_addr转换包含IPv4的字符串点分十进制地址转换成一个适当的地址 IN_ADDR结构
mAddrEnd.S_un.S_addr = inet_addr("192.168.1.255"); //inet_addr转换包含IPv4的字符串点分十进制地址转换成一个适当的地址 IN_ADDR结构
for (in_addr i = mAddrStart;i.S_un.S_un_b.s_b4<mAddrEnd.S_un.S_un_b.s_b4; i.S_un.S_un_b.s_b4++) {
printf("%s
", inet_ntoa(i));
CreateThread(NULL, 0, ThreadProc, (LPVOID)i.S_un.S_addr, 0, NULL);
}
Sleep(5000);
return 0;
}
参考文章:https://blog.51cto.com/0x007/1619183
参考文章:https://www.cnblogs.com/17bdw/p/6166497.html