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

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

 

你可能感兴趣的:(Linux下遍历目录下的所有文件(获取mac))