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

    运行结果如下:

  • 相关阅读:
    win10下vs2015配置Opencv3.1.0过程详解
    Int16, Int32, Int64 范围
    Microsoft Language and Locale Codes(微软语言和地区代码汇总)
    Azure china服务状态报告查看网址
    Azure IOT (EventHub + Stream Analytics + Table Storage)的使用
    java 继承extends 的相关知识点
    final
    java 垃圾回收机制
    Java 抽象类
    重载与重写、多态——java
  • 原文地址:https://www.cnblogs.com/fellow1988/p/6151518.html
Copyright © 2011-2022 走看看