Function for obtaining all interfaces and IP addresses of a Local Machine

Source: Internet
Author: User
Function for obtaining all interfaces and IP addresses of a Local Machine

I have been busy with a program recently. To protect all the IP addresses on my machine, I need to get them.
Although there is no arp in IPv6, I always want to write code in a Protocol version, so I must be able to get the IPv6 address anyway.
As long as IPv4 is used, there is no need to write this article.
The first thing I want to consider is to use NETLINK for access, but I don't want to use it now, because I have finished writing the program in a few days, and I will re-write the old ioctl with NETLINK.
Think of the book (UNPv3) that there is a getifaddrs function in BSD, I just ran it, and my machine also had it (LINUX ). Read the manual page and ifaddrs. h
The file is confused again. Can such a function support IPv6. because the Members in the struct ifaddrs structure only have the struct sockaddr pointer, And the V4 can be installed. V6 address
OK?
I searched it up and found an egg (simple) code in a foreign email list. The struct sockaddr * ifa_addr member can be directly
The value of the sa_family member in it is directly converted to the corresponding type. I feel much better. It's okay to get it. If it doesn't work, I feel that so many addresses are returned. You can use the lo interface address
It's useless. Imagine that the actual code seldom cares about the return interface, and you can find another way to filter it out. Look at the struct ifaddrs, which is obviously the type of the linked list node (too self-righteous)
I thought it was a real linked list. I just needed to correct it.
So I was busy for a long time and wrote a small function. This is a snippet: (this is a little abnormal, and it is not guaranteed)
While (ifa ){
Tmp = ifa;
Tmp-> ifa_next = NULL;
If (ifa-> ifa_addr-> sa_family! = Family ){
If (family! = AF_UNSPEC & (ifa-> ifa_addr = NULL | (ifa-> ifa_flags & IFF_UP) = 0) |! Strcmp (ifa-> ifa_name, "lo "))){
Freeifaddrs (tmp );
If (flag ){
Ifaddrs = ifa-> ifa_next;/** never get here twice **/
Flag = 0;
}
}
Ifa = ifa-> ifa_next;
}
}
The address type is used as a parameter to obtain all the interface IP addresses of all activities except the return address of the specified type on the machine,
Then we found that there were always errors. Because the first return is the V4 return address, I want to release it. When running, the following message is always displayed:
Lo: 127.0.0.1
Eth0: 10.0.119.163
Lo: 1
Eth0: fe80: 203: dff: fe2f: 9149
* ** Glibc detected ** d: free (): invalid pointer: 0x0804a4d4 ***
======= Backtrace: ============
/Lib/libc. so.6 [0xb7eda911]
/Lib/libc. so.6 (_ libc_free + 0x84) [0xb7edbf84]
/Lib/libc. so.6 (freeifaddrs + 0x1d) [0xb7f512dd]
D [0x8048989]
D [0x80486a5]
/Lib/libc. so.6 (_ libc_start_main + 0xdc) [0xb7e8c87c]
D [0x8048491]
======= Memory map: ========
08048000-08049000 r-xp 00000000 48637/home/souldump/bin/d
08049000-0804a000 rw-p 00000000 07 48637/home/souldump/bin/d
0804a000-0806b000 rw-p 0804a000 00:00 0 [heap]
B7d00000-b7d21000 rw-p b7d00000 0
B7d21000-b7e00000 --- p b7d21000 00:00 0
B7e76000-b7e77000 rw-p b7e76000 0
B7e77000-b7f90000 r-xp 00000000 0:05 16184/lib/libc-2.4.so
B7f90000-b7f92000 r -- p 00118000 0:05 16184/lib/libc-2.4.so
B7f92000-b7f94000 rw-p 0011a000 0:05 16184/lib/libc-2.4.so
B7f94000-b7f98000 rw-p b7f94000 0
B7fab000-b7fb5000 r-xp 00000000 0:05 20108/lib/libgcc_s.so.1
B7fb5000-b7fb6000 rw-p 00009000 0:05 20108/lib/libgcc_s.so.1
B7fb6000-b7fb7000 rw-p b7fb6000 0
B7fb7000-b7fd1000 r-xp 00000000 0:05 16177/lib/ld-2.4.so
B7fd1000-b7fd3000 rw-p 00019000 0:05 16177/lib/ld-2.4.so
Bfb2b000-bfb41000 rw-p bfb2b000 0 [stack]
Ffffe000-fffff000 --- p 00000000 00:00 0 [vdso]
Abandoned

The pointer is invalid because it is not a real linked list.
So I turned to the idea of looking at the GLIBC code, and I did not know the answer to all the questions in the code.
Quickly open the previous installation of LFS glbc-2.3.6 source code.

Searched under glibc-2.3.6/glibc-2.3.6/sysdeps/unix/sysv/linux/ifaddrs. c
Found the implementation of getifaddrs, the first eye is depressed, still implemented using NETLINK. I did not bother to do this until I wrote it myself.
It defines such a structure to ensure the space of each interface. This is why IPv6 can be converted.
Struct ifaddrs_storage
{
Struct ifaddrs ifa;
Union
{
/* Save space for the biggest of the four used sockaddr types and
Avoid a lot of casts .*/
Struct sockaddr sa;
Struct sockaddr_ll sl;
Struct sockaddr_in s4;
Struct sockaddr_in6 s6;
} Addr, netmask, broadaddr;
Char name [IF_NAMESIZE + 1];
};
The general process is as follows: if NETLINK is supported, send a request. Otherwise, call fallback_getifaddrs (previously implemented by getifaddrs)
Function implementation only supports IPv4 (ioctl is used for one interface ). (I remember someone in the mail list asked this function from the version of glibc.
I started to support IPv6, but the Japanese did not seem to have said that I only wanted to check the next version .), Then, the first time the system quickly traverses and processes the returned data,
Determine the number of interfaces and addresses to allocate space. Next, traverse the data again and initialize the ifa_next of each struct ifaddrs structure.
Pointer (using map_newlink), the value of the corresponding item memcpy is passed according to each rtattr structure type.
If you are interested, just read the freeifaddrs function. Only free (ifa.
I finally figured out that since NETLINK is still used, it is not easy to do this time. With the experience of operating the route table last time and the glibc code
The library function is changed and encapsulated into a new function, which will be used later. The AF_INET, AF_INET6, AF_UNSPEC parameters are used,

This is the code:

Shell code
  1. # Include <stdio. h>
  2. # Include <stdlib. h>
  3. # Include <stdbool. h>
  4. # Include <string. h>
  5. # Include <unistd. h>
  6. # Include <sys/socket. h>
  7. # Include <net/if. h>
  8. # Include <netinet/in. h>
  9. # Include <sys/types. h>
  10. # Include <linux/netlink. h>
  11. # Include <linux/rtnetlink. h>
  12. # Include <assert. h>
  13. # Include <errno. h>
  14. # Include <ifaddrs. h>
  15. # Include <netpacket/packet. h>
  16. Void print_ip (struct ifaddrs * ifaddrs );
  17. /** NOTE! Caller must call freeifaddrs () after the use the pointer **/
  18. Int get_local_ip (struct ifaddrs ** ifap, int family );
  19. # Define IS_UNSPEC (family) (family = AF_UNSPEC)
  20. # Define NO_ADDRS (ifa) (ifa-> ifa_addr = NULL)
  21. # Define FAMILY_ OK (ifa) (ifa-> ifa_addr-> sa_family = AF_INET | \
  22. Ifa-> ifa_addr-> sa_family = AF_INET6)
  23. # Define IN_FAMILY (ifa, family) (ifa-> ifa_addr-> sa_family = family)
  24. # Define TEST_FLAG (ifa, flag) (ifa-> ifa_flags | flag)
  25. # Define IS_LOOPBACK (ifa) (strncmp (ifa-> ifa_name, "lo", 2) = 0)
  26. # Define move_ptr (ifa, tmp) do {ifa-> ifa_next = tmp-> ifa_next ;\
  27. Ifa-> ifa_name = tmp-> ifa_name ;\
  28. Ifa-> ifa_flags = tmp-> ifa_flags ;\
  29. Ifa-> ifa_addr = tmp-> ifa_addr ;\
  30. Ifa-> ifa_netmask = tmp-> ifa_netmask ;\
  31. If (TEST_FLAG (ifa, IFF_BROADCAST ))\
  32. Ifa-> ifa_broadaddr = tmp-> ifa_broadaddr ;\
  33. Else if (TEST_FLAG (ifa, IFF_POINTOPOINT ))\
  34. Ifa-> ifa_dstaddr = tmp-> ifa_dstaddr ;\
  35. } While (0)
  36. Int main ()
  37. {
  38. Struct ifaddrs * ifa, * ifaddrs;
  39. Struct ifaddrs * ifb, * ifc;
  40. Printf ("AF_INET \ n ");
  41. Get_local_ip (& ifa, AF_INET );
  42. Print_ip (ifa );
  43. Printf ("AF_INET6 \ n ");
  44. Get_local_ip (& ifb, AF_INET6 );
  45. Print_ip (ifb );
  46. Printf ("AF_UNSPEC \ n ");
  47. Get_local_ip (& ifc, AF_UNSPEC );
  48. Print_ip (ifc );
  49. }
  50. Void
  51. Print_ip (struct ifaddrs * ifaddrs)
  52. {
  53. Struct ifaddrs * ifa;
  54. Struct sockaddr_in * sin;
  55. Struct sockaddr_in6 * sin6;
  56. Char buf [INET6_ADDRSTRLEN];
  57. For (ifa = ifaddrs; ifa! = NULL; ifa = ifa-> ifa_next)
  58. {
  59. If (ifa-> ifa_addr = NULL) continue;
  60. If (ifa-> ifa_flags & IFF_UP) = 0) continue;
  61. If (ifa-> ifa_addr-> sa_family = AF_INET)
  62. {
  63. Sin = (struct sockaddr_in *) (ifa-> ifa_addr );
  64. If (inet_ntop (ifa-> ifa_addr-> sa_family, (void *) & (sin-> sin_addr), buf, sizeof (buf) = NULL)
  65. {
  66. Printf ("% s: inet_ntop failed! \ N ", ifa-> ifa_name );
  67. }
  68. Else
  69. {
  70. Printf ("% s: % s \ n", ifa-> ifa_name, buf );
  71. }
  72. }
  73. Else if (ifa-> ifa_addr-> sa_family = AF_INET6)
  74. {
  75. Sin6 = (struct sockaddr_in6 *) (ifa-> ifa_addr );
  76. If (inet_ntop (ifa-> ifa_addr-> sa_family, (void *) & (sin6-> sin6_addr), buf, sizeof (buf) = NULL)
  77. {
  78. Printf ("% s: inet_ntop failed! \ N ", ifa-> ifa_name );
  79. }
  80. Else
  81. {
  82. Printf ("% s: % s \ n", ifa-> ifa_name, buf );
  83. }
  84. }
  85. }
  86. }
  87. Int get_local_ip (struct ifaddrs ** ifap, int family)
  88. {
  89. Int n;
  90. Bool change = 0;
  91. Char * name;
  92. Struct ifaddrs * ifa;
  93. Struct ifaddrs * tmp;
  94. Struct sockaddr_in * sin;
  95. Struct sockaddr_in6 * sin6;
  96. Char buf [INET6_ADDRSTRLEN];
  97. N = getifaddrs (& ifa );
  98. If (n! = 0)
  99. Return-1;
  100. * Ifap = ifa;
  101. For (ifa; (tmp = ifa )! = NULL; ifa = ifa-> ifa_next ){
  102. While (tmp & (IS_LOOPBACK (tmp) |
  103. NO_ADDRS (tmp) | (! TEST_FLAG (tmp, IFF_UP) |
  104. (FAMILY_ OK (tmp )&&(! IN_FAMILY (tmp, family ))&&(! IS_UNSPEC (family) |
  105. ! FAMILY_ OK (tmp ))){
  106. Change = true;
  107. Tmp = tmp-> ifa_next;
  108. }
  109. If (change ){
  110. If (tmp)
  111. Move_ptr (ifa, tmp );
  112. Else
  113. Memset (ifa, 0, sizeof (struct ifaddrs ));
  114. /** An alternative way is use these instead:
  115. Ifa-> ifa_next = NULL;
  116. Ifa-> ifa_name = NULL;
  117. Ifa-> ifa_addr = NULL;
  118. Ifa-> ifa_netmask = NULL;
  119. If (TEST_FLAG (ifa, IFF_BROADCAST ))
  120. Ifa-> ifa_broadaddr = NULL;
  121. Else if (TEST_FLAG (ifa, IFF_POINTOPOINT ))
  122. Ifa-> ifa_dstaddr = NULL;
  123. **/
  124. Change = false;
  125. }
  126. }
  127. /** I think even * ifap now is NULL after check, we shoshould not free the space either.
  128. Since user who called this routine will call freeifaddrs () too, The space will be free safely .**/
  129. Return 0;
  130. }

From: http://www.linuxsir.org/bbs/thread284220.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.