Want more features on Pastebin? Sign Up, it's FREE!
Guest

Untitled

By: a guest on Jul 22nd, 2011  |  syntax: C  |  size: 2.13 KB  |  views: 225  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. #include <sys/types.h>
  2. #include <netinet/in.h>
  3. #include <sys/socket.h>
  4. #include <ifaddrs.h>
  5. #include <net/ethernet.h>
  6. #include <linux/if_packet.h>
  7. #include <stdio.h>
  8. void
  9. print_sockaddr(struct sockaddr* addr,const char *name)
  10. {
  11.     char addrbuf[128] ;
  12.  
  13.     addrbuf[0] = 0;
  14.     if(addr->sa_family == AF_UNSPEC)
  15.         return;
  16.     switch(addr->sa_family) {
  17.         case AF_INET:
  18.             inet_ntop(addr->sa_family,&((struct sockaddr_in*)addr)->sin_addr,addrbuf,sizeof(struct sockaddr_in));
  19.             break;
  20.         case AF_INET6:
  21.             inet_ntop(addr->sa_family,&((struct sockaddr_in6*)addr)->sin6_addr,addrbuf,sizeof(struct sockaddr_in6));
  22.             break;
  23.         case AF_PACKET:  {
  24.             struct sockaddr_ll *s = (struct sockaddr_ll*)addr;
  25.             int i;
  26.             int len = 0;
  27.             for(i = 0; i < 6; i++)
  28.                 len+=sprintf(addrbuf+len,"%02X%s",s->sll_addr[i],i < 5 ? ":":"");
  29.             len+=sprintf(addrbuf+len,"\nInterface Index %d Physical layer protocol %u Header type %u Packet type %u Length of address %u",s->sll_ifindex,s->sll_protocol,s->sll_hatype, s->sll_pkttype,s->sll_halen);
  30.  
  31.         }
  32.  
  33.             break;
  34.         default:
  35.             sprintf(addrbuf,"Unknown (%d)",(int)addr->sa_family);
  36.             break;
  37.  
  38.     }
  39.     printf("%-16s %s\n",name,addrbuf);
  40. }
  41.  
  42. void
  43. print_ifaddr(struct ifaddrs *addr)
  44. {
  45.     char addrbuf[128] ;
  46.  
  47.     addrbuf[0] = 0;
  48.     printf("%-16s %s\n","Name",addr->ifa_name);
  49.     if(addr->ifa_addr != NULL)
  50.         print_sockaddr(addr->ifa_addr,"Address");
  51.     if(addr->ifa_netmask != NULL)
  52.         print_sockaddr(addr->ifa_netmask,"Netmask");
  53.     if(addr->ifa_broadaddr != NULL)
  54.         print_sockaddr(addr->ifa_broadaddr,"Broadcast addr.");
  55.     if(addr->ifa_dstaddr != NULL)
  56.         print_sockaddr(addr->ifa_dstaddr,"Peer addr.");
  57.     puts("");
  58. }
  59.  
  60.  
  61. int main(int argc,char *argv[])
  62. {
  63.     struct ifaddrs *addrs,*tmp;
  64.  
  65.     if(getifaddrs(&addrs) != 0) {
  66.         perror("getifaddrs");
  67.         return 1;
  68.     }
  69.     for(tmp = addrs; tmp ; tmp = tmp->ifa_next) {
  70.         print_ifaddr(tmp);
  71.     }
  72.  
  73.     freeifaddrs(addrs);
  74.  
  75.     return 0;
  76. }
clone this paste RAW Paste Data