// CheckMacAddress.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <stdio.h>
#include <Windows.h>
#include <iphlpapi.h>
#define IP_LOCALHOST 0x0100007F
#define MAX_ADDR_LEN 18
void print_ip(DWORD nAddr)
{
printf("%d.%d.%d.%d\n", nAddr & 0x000000FF, (nAddr & 0x0000FF00) >> 8, (nAddr & 0x00FF0000) >> 16, (nAddr & 0xFF000000) >> 24);
}
int main()
{
char macAddr[MAX_ADDR_LEN] = { 0 };
DWORD status = NO_ERROR;
ULONG size = 0;
MIB_IPADDRTABLE *ip_table = NULL;
status = GetIpAddrTable(ip_table, &size, 0);
if (status == ERROR_INSUFFICIENT_BUFFER) {
ip_table = (MIB_IPADDRTABLE *)malloc(size);
status = GetIpAddrTable(ip_table, &size, 0);
if (status == NO_ERROR) {
for (int i = 0; i < ip_table->dwNumEntries; ++i)
{
if (IP_LOCALHOST != ip_table->table[i].dwAddr)
{
print_ip(ip_table->table[i].dwAddr);
MIB_IFROW iInfo;
BYTE byMAC[6] = { 0, 0, 0, 0, 0, 0 };
memset(&iInfo, 0, sizeof(MIB_IFROW));
iInfo.dwIndex = ip_table->table[i].dwIndex;
GetIfEntry(&iInfo);
if (MIB_IF_TYPE_ETHERNET == iInfo.dwType)
{
memcpy(&byMAC, iInfo.bPhysAddr, iInfo.dwPhysAddrLen);
sprintf(macAddr, "%02x-%02x-%02x-%02x-%02x-%02x", byMAC[0], byMAC[1], byMAC[2], byMAC[3], byMAC[4], byMAC[5]);
}
}
}
}
else {
printf("Unable to read IP table from system\n");
}
free(ip_table);
}
else {
printf("Unable to determine number of entries in IP table\n");
}
printf("MAC Address is %s\n", macAddr);
return 0;
}
C/C++获取计算机MAC地址
最新推荐文章于 2024-07-07 20:34:25 发布