C/C++获取计算机MAC地址

// 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;
}

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值