Guest User

Untitled

a guest
May 25th, 2018
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.60 KB | None | 0 0
  1.  
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <unistd.h>
  5. #include <string.h>
  6. #include <sys/socket.h>
  7. #include <sys/ioctl.h>
  8. #include <linux/if.h>
  9. #include <netinet/in.h>
  10. #include <arpa/inet.h>
  11. #include "setup_interfaces.h"
  12. #include "sysfs_reader.h"
  13.  
  14. struct net_iface* get_all_interfaces()
  15. {
  16.     struct ifreq *ifr;
  17.     struct ifconf ifc;
  18.     int s;
  19.     int numif;
  20.  
  21.     memset(&ifc, 0, sizeof(ifc));
  22.     ifc.ifc_ifcu.ifcu_req = NULL;
  23.     ifc.ifc_len = 0;
  24.  
  25.     if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
  26.         perror("socket");
  27.         return NULL;
  28.     }
  29.  
  30.     if (ioctl(s, SIOCGIFCONF, &ifc) < 0) {
  31.             perror("ioctl");
  32.         return NULL;
  33.     }
  34.  
  35.     if ((ifr = malloc(ifc.ifc_len)) == NULL) {
  36.             perror("malloc");
  37.             return NULL;
  38.     }
  39.  
  40.     ifc.ifc_ifcu.ifcu_req = ifr;
  41.  
  42.     if (ioctl(s, SIOCGIFCONF, &ifc) < 0) {
  43.         perror("ioctl");
  44.         return NULL;
  45.     }
  46.  
  47.     close(s);
  48.  
  49.     numif = ifc.ifc_len / sizeof(struct ifreq);
  50.  
  51.     if (!numif) {
  52.         free(ifr);
  53.         return NULL;
  54.     }
  55.  
  56.     struct net_iface* iflist;
  57.  
  58.     if ((iflist = malloc(sizeof(struct net_iface) * numif)) == NULL) {
  59.         perror("malloc");
  60.         return NULL;
  61.     }
  62.  
  63.     int sysfs_avail = is_sysfs_available();
  64.  
  65.     int i;
  66.  
  67.     for (i = 0; i < numif; i++) {
  68.         struct ifreq *r = &ifr[i];
  69.         struct sockaddr_in *sin = (struct sockaddr_in *)&r->ifr_addr;
  70.  
  71.         iflist[i].if_idx = r->ifr_ifindex;
  72.         strncpy(iflist[i].if_name, r->ifr_name, IFNAMSIZ);
  73.  
  74.         if (sysfs_avail) {
  75.             iflist[i].get_stat = get_stat_sysfs;
  76.         }
  77.  
  78.         inet_ntop(AF_INET, &sin->sin_addr, iflist[i].str_ip4_addr, INET_ADDRSTRLEN);
  79.  
  80.         if (i) {
  81.             iflist[i-1].next = &iflist[i];
  82.         }
  83.     }
  84.  
  85.     free(ifr);
  86.  
  87.     return iflist;
  88. }
Add Comment
Please, Sign In to add comment