code_junkie

Finding an IP from an interface name

Nov 12th, 2011
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.32 KB | None | 0 0
  1. #include <sys/types.h>
  2. #include <sys/socket.h>
  3. #include <sys/ioctl.h>
  4. #include <net/if.h>
  5. #include <netinet/in.h>
  6. #include <arpa/inet.h>
  7. #include <string.h>
  8. #include <stdio.h>
  9. #include <unistd.h>
  10.  
  11. /**
  12. * getIPv4()
  13. *
  14. * This function takes a network identifier such as "eth0" or "eth0:0" and
  15. * a pointer to a buffer of at least 16 bytes and then stores the IP of that
  16. * device gets stored in that buffer.
  17. *
  18. * it return 0 on success or -1 on failure.
  19. *
  20. * Author: Jaco Kroon <[email protected]>
  21. */
  22. int getIPv4(const char * dev, char * ipv4) {
  23. struct ifreq ifc;
  24. int res;
  25. int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
  26.  
  27. if(sockfd < 0)
  28. return -1;
  29. strcpy(ifc.ifr_name, dev);
  30. res = ioctl(sockfd, SIOCGIFADDR, &ifc);
  31. close(sockfd);
  32. if(res < 0)
  33. return -1;
  34. strcpy(ipv4, inet_ntoa(((struct sockaddr_in*)&ifc.ifr_addr)->sin_addr));
  35. return 0;
  36. }
  37.  
  38.  
  39. int main() {
  40. char ip[16];
  41. if(getIPv4("eth0", ip) == 0)
  42. printf("IPv4: %sn", ip);
  43. else
  44. printf("No IPn");
  45. return 0;
  46. }
  47.  
  48. ifconfig eth0 | grep 'inet addr' | sed -e 's/:/ /' | awk '{print $3}'
  49.  
  50. ifconfig | egrep '^[^ ]' | awk '{print $1}'
  51.  
  52. for x in `ifconfig | egrep '^[^ ]' | awk '{print $1}'`; do
  53. echo -n "${x}"
  54. echo -n " "
  55. ifconfig "${x}" | grep 'inet addr' | sed -e 's/:/ /' | awk '{print $3}'
  56. done
Add Comment
Please, Sign In to add comment