通过 IP Helper API 中的 SendARP 发送 ARP 请求来获取 MAC 地址,简单方便,缺点是不能跨越网关。
#include
#include
#include
#pragma comment(lib , "IpHlpApi.lib")
#pragma comment(lib , "WS2_32.lib")
int main(int argc,char * argv[])
{
int iReturn;
DWORD dwIP;
BYTE byMAC[6];
DWORD dwLen;
WSADATA WsaData;
WSAStartup(MAKEWORD(2, 0), &WsaData);
__try
{
printf("IP2MAC Ver 1.0 -- Get MAC address from IP address though ARP request./n/n");
if (argc != 2)
{
printf("Usage: %s /n", argv[0]);
__leave;
}
dwIP = inet_addr(argv[1]);
if (dwIP == INADDR_NONE)
{
printf("Invalid IP address: %s./n", argv[1]);
__leave;
}
// 发送ARP查询包获得 MAC 地址
dwLen = 6;
iReturn = SendARP(dwIP, 0, (PULONG) &byMAC, &dwLen);
if (iReturn != NO_ERROR)
{
printf("Error: Send ARP request. /nBe sure that connectting to %s need no gateway./n", argv[1]);
__leave;
}
printf("%.2X-%.2X-%.2X-%.2X-%.2X-%.2X/n",
byMAC[0], byMAC[1], byMAC[2], byMAC[3], byMAC[4], byMAC[5]);
}
__finally
{
WSACleanup();
}
return 0;
}