小言_互联网的博客

Linux下遍历目录下的所有文件(获取mac)

388人阅读  评论(0)
#include <net/if.h>
#include <sys/ioctl.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define ETH_NAME    "enp2s0"  //如果要获取其他网卡的地址,将这个换为其他网卡名称,比如eth0

void get_mac(char * mac_a,char *netname)
{
    int                 sockfd;
    struct ifreq        ifr;

    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd == -1) {
        perror("socket error");
        exit(1);
    }
    strncpy(ifr.ifr_name, netname, IFNAMSIZ);      //Interface name

    if (ioctl(sockfd, SIOCGIFHWADDR, &ifr) == 0) 
    {  //SIOCGIFHWADDR 获取hardware address
        memcpy(mac_a, ifr.ifr_hwaddr.sa_data, 6);

    }
}
#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <stdlib.h>
int  PrintDir(char *dir, int depth)
{
  DIR *dp;
  unsigned char this_mac[6];
  struct dirent *entry;
  struct stat statbuf;
 
  if ((dp = opendir(dir)) == NULL)
  {
    fprintf(stderr, "Cannot open directory: %s\n", dir);
    return;
  }
  chdir(dir);
  while ((entry = readdir(dp)) != NULL)
  {
    lstat(entry->d_name, &statbuf);
    if (S_ISDIR(statbuf.st_mode))
    {
      if (strcmp(".", entry->d_name) == 0 || strcmp("..", entry->d_name) == 0)
        continue;
     // printf("%*s%s/\n", depth, "", entry->d_name);
    // PrintDir(entry->d_name, depth + 4);
   //   get_mac(this_mac, entry->d_name);this_mac[6]=0;
     // printf("%s: %s\n",entry->d_name,this_mac);
    }
    else
    {
        get_mac(this_mac, entry->d_name);
       printf("%s: %02x:%02x:%02x:%02x:%02x:%02x\n",entry->d_name,this_mac[0],this_mac[1],this_mac[2],this_mac[3],this_mac[4],this_mac[5]);
    
             return 1;
        
    }
      //printf("%*s%s\n", depth, "", entry->d_name);
  }
  chdir("..");
  closedir(dp);
  return 0;
}


int main(int argc, char* argv[])
{
  PrintDir("/sys/class/net/", 0)
  return 0;
}

 


转载:https://blog.csdn.net/mao0514/article/details/101595463
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场