Linux下遍歷目錄下的所有文件(獲取mac)

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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章