zoukankan      html  css  js  c++  java
  • 获取平台所有接口的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));
            }
          }
        }
      }
    }

    运行结果如下:

  • 相关阅读:
    FATFS 初学之 f_open/ f_close
    前端JQuery(二)
    前端JQuery(一)
    8.22MySQL(五)pymysql模块、sql注入问题
    8.21MySQL(四)基本查询语句及方法、连表、子查询
    8.20MySQL(三)外键
    8.19MySQL(二)
    8.16MySQL(一)
    8.15并发编程(四)
    8.14并发编程(三)
  • 原文地址:https://www.cnblogs.com/fellow1988/p/6151518.html
Copyright © 2011-2022 走看看