鱼C论坛

 找回密码
 立即注册
查看: 848|回复: 2

[技术交流] linux用C++,如何用获取网口设备mac地址?

[复制链接]
发表于 2020-7-17 15:07:52 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
linux用C++,如何用获取网口设备mac地址?
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-7-17 20:26:44 | 显示全部楼层
  1. #include <sys/ioctl.h>
  2. #include <net/if.h>
  3. #include <netinet/in.h>
  4. #include <string.h>
  5. #include <stdio.h>

  6. void dump_macaddress(char* address) {
  7.     printf("%02x", address[0]);
  8.     for (int i = 1; i < 6; i++) {
  9.         printf(":%2x", address[i] & 0xff);
  10.     }
  11.     printf("\n");
  12. }

  13. int main() {
  14.     struct ifreq ifr;
  15.     struct ifconf ifc;
  16.     char buf[1024];

  17.     int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
  18.     if (sock == -1) { /* handle error*/ };

  19.     ifc.ifc_len = sizeof(buf);
  20.     ifc.ifc_buf = buf;
  21.     if (ioctl(sock, SIOCGIFCONF, &ifc) == -1) { /* handle error */ }

  22.     struct ifreq *it = ifc.ifc_req;
  23.     const struct ifreq *const end = it + (ifc.ifc_len / sizeof(struct ifreq));

  24.     for (; it != end; ++it) {
  25.         strcpy(ifr.ifr_name, it->ifr_name);
  26.         if (ioctl(sock, SIOCGIFFLAGS, &ifr) == 0) {
  27.             if (!(ifr.ifr_flags & IFF_LOOPBACK)) { // don't count loopback
  28.                 if (ioctl(sock, SIOCGIFHWADDR, &ifr) == 0) {
  29.                     dump_macaddress(ifr.ifr_hwaddr.sa_data);
  30.                 }
  31.             }
  32.         } else { /* handle error */ }
  33.     }
  34. }
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-12-17 15:17:30 | 显示全部楼层
请问如何只获取当前本机的MAC地址呢?上面的代码会把全部MAC地址都得到,包括虚拟网卡的地址
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-7-7 02:40

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表