markizano

getifaddr.c

Oct 15th, 2012
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.93 KB | None | 0 0
  1. #include <arpa/inet.h>
  2. #include <sys/socket.h>
  3. #include <netdb.h>
  4. #include <ifaddrs.h>
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <unistd.h>
  8. #include <string.h>
  9.  
  10. int Usage () {
  11.     printf("Usage: getifaddr [ifaddr] [inet|inet6]\nDefaults to eth0/inet.\n");
  12.     return 8;
  13. }
  14.  
  15. int main(int argc, char *argv[]) {
  16.     struct ifaddrs *ifaddr, *ifa;
  17.     int family, s, inet;
  18.     char host[NI_MAXHOST], *iface;
  19.  
  20.     iface = NULL; inet = AF_INET;
  21.     if ( argc >= 2 ) {
  22.         if ( !strcmp(argv[1], "-h") || !strcmp(argv[1], "--help") ) {
  23.             return Usage();
  24.         }
  25.     } else if ( argc <= 2 ) {
  26.         return Usage();
  27.     }
  28.  
  29.     if ( argc >= 2 ) {
  30.         iface = strndup(argv[1], strlen(argv[1]));
  31.     }
  32.  
  33.     if ( argc >= 3 ) {
  34.         if ( !strcmp(argv[2], "inet6") ) {
  35.             inet = AF_INET6;
  36.         }
  37.     }
  38.  
  39.     if ( iface == NULL ) {
  40.         iface = malloc(4);
  41.         if ( iface == NULL ) return 4;
  42.         strncpy(iface, "eth0", 4);
  43.     }
  44.  
  45.     if (getifaddrs(&ifaddr) == -1) {
  46.         perror("getifaddrs");
  47.         exit(EXIT_FAILURE);
  48.     }
  49.  
  50.     memset(host, 0, sizeof host);
  51.  
  52.     /* Walk through linked list, maintaining head pointer so we can free list later */
  53.  
  54.     for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
  55.         if (ifa->ifa_addr == NULL) continue;
  56.         family = ifa->ifa_addr->sa_family;
  57.  
  58.         if ( family == AF_PACKET ) continue;
  59.  
  60.         /* Display interface name and family (including symbolic
  61.             form of the latter for the common families) */
  62.         if ( !strcmp(ifa->ifa_name, iface) ) {
  63.             if ( family == inet ) {
  64.                 s = getnameinfo(ifa->ifa_addr, ( (family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6) ), host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
  65.                 if (s != 0) {
  66.                     fprintf(stderr, "getnameinfo() failed: %s\n", gai_strerror(s));
  67.                     exit(EXIT_FAILURE);
  68.                 }
  69.             }
  70.  
  71.             printf( "%s\n", host );
  72.             freeifaddrs(ifaddr);
  73.             free(iface);
  74.             return 0;
  75.         }
  76.     }
  77.  
  78.     fprintf(stderr, "Could not find devivce.\n");
  79.     freeifaddrs(ifaddr);
  80.     free(iface);
  81.     exit(EXIT_SUCCESS);
  82. }
Advertisement
Add Comment
Please, Sign In to add comment