• 获取平台所有接口的IP和MAC地址


    我们有时候会有获取网口的IP和MAC地址的需求。可以通过ioctl来获取。

    #include <sys/ioctl.h>
    #include <net/if.h>
    #include <arpa/inet.h>
    #include <string.h>
    #include <stdio.h>
    #include <sys/types.h>
    #include <sys/socket.h>
    void main(void)
    {
      struct ifreq ifr;
      struct ifconf ifc;
      char buff[1024];
      int fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
      ifc.ifc_len = sizeof(buff);
      ifc.ifc_buf = buff;
      ioctl(fd, SIOCGIFCONF, &ifc);//获取所有的网口信息
      struct ifreq *it = ifc.ifc_req;
      const struct ifreq* const end = it + ifc.ifc_len/sizeof(struct ifreq);
      for (; it != end; it++)//遍历网口
      {
        strncpy(ifr.ifr_name, it->ifr_name, strlen(it->ifr_name) + 1);//网口名称,如“eth0”“ra0”
        printf("ifr_name :%s ", ifr.ifr_name);
        if (ioctl(fd, SIOCGIFFLAGS, &ifr) == 0)
        {
          if (!(ifr.ifr_flags & IFF_LOOPBACK))//忽略lo
          {
            if (ioctl(fd, SIOCGIFHWADDR, &ifr) == 0)//获取MAC
            {
              unsigned char mac[6];
              memcpy(mac, ifr.ifr_hwaddr.sa_data, 6);
              printf("mac: %02x:%02x:%02x:%02x:%02x:%02x ",mac[0],mac[1],mac[2],mac[3], mac[4], mac[5]);
            }
            if (ioctl(fd, SIOCGIFADDR, &ifr) == 0)//获取IP
            {
              struct sockaddr_in sin;
              memcpy(&sin, &ifr.ifr_addr, sizeof(struct sockaddr_in));
              printf("ip: %s ", inet_ntoa(sin.sin_addr));
            }
          }
        }
      }
    }

    运行结果如下:

  • 相关阅读:
    04:求整数的和与均值
    03:均值
    02:财务管理
    C8-3 三角形还是长方形? (100/100 分数)
    C8-2 圆的周长和面积 (100/100 分数)
    C8-1 复数加减乘除 (100/100 分数)
    C7-3 用类实现a+b (100/100 分数)
    C7-2 多继承 (100/100 分数)
    C7-1 账户类(100/100)
    数组第k小数
  • 原文地址:https://www.cnblogs.com/fellow1988/p/6151518.html
Copyright © 2020-2023  润新知