[ Team LiB ] Previous Section Next Section

17.6 get_ifi_info Function

Since many programs need to know all the interfaces on a system, we will develop a function of our own named get_ifi_info that returns a linked list of structures, one for each interface that is currently "up." In this section, we will implement this function using the SIOCGIFCONF ioctl, and in Chapter 18, we will develop a version using routing sockets.

FreeBSD provides a function named getifaddrs with similar functionality.

Searching the entire FreeBSD 4.8 source tree shows that 12 programs issue the SIOCGIFCONF ioctl to determine the interfaces present.

We first define the ifi_info structure in a new header named unpifi.h, shown in Figure 17.5.

Figure 17.5 unpifi.h header.

lib/unpifi.h

 1 /* Our own header for the programs that need interface configuration info.
 2    Include this file, instead of "unp.h". */

 3 #ifndef __unp_ifi_h
 4 #define __unp_ifi_h

 5 #include     "unp.h"
 6 #include     <net/if.h>

 7 #define IFI_NAME     16            /* same as IFNAMSIZ in <net/if.h> */
 8 #define IFI_HADDR     8            /* allow for 64-bit EUI-64 in future */

 9 struct  ifi_info {
10     char     ifi_name[IFI_NAME];   /* interface name, null-terminated */
11     short    ifi_index;            /* interface index */
12     short    ifi_mtu;              /* interface MTU */
13     u_char   ifi_haddr[IFI_HADDR];     /* hardware address */
14     u_short  ifi_hlen;             /* # bytes in hardware address: 0, 6, 8 */
15     short    ifi_flags;            /* IFF_xxx constants from <net/if.h> */
16     short    ifi_myflags;          /* our own IFI_xxx flags */
17     struct  sockaddr *ifi_addr;    /* primary address */
18     struct  sockaddr *ifi_brdaddr;     /* broadcast address */
19     struct  sockaddr *ifi_dstaddr;     /* destination address */
20     struct  ifi_info *ifi_next;    /* next of these structures */
21 };

22 #define IFI_ALIAS    1             /* ifi_addr is an alias */

23                      /* function prototypes */
24 struct ifi_info *get_ifi_info(int, int);
25 struct ifi_info *Get_ifi_info(int, int);
26 void    free_ifi_info(struct ifi_info *);

27 #endif  /* __unp_ifi_h */

9–21 A linked list of these structures is returned by our function, each structure's ifi_next member pointing to the next one. We return in this structure just the information that a typical application is probably interested in: the interface name, the interface index, the MTU, the hardware address (e.g., an Ethernet address), the interface flags (to let the application determine if the interface supports broadcasting or multicasting, or is a point-to-point interface), the interface address, the broadcast address, and the destination address for a point-to-point link. All the memory used to hold the ifi_info structures, along with the socket address structures contained within, are obtained dynamically. Therefore, we also provide a free_ifi_info function to free all this memory.

Before showing the implementation of our get_ifi_info function, we show a simple program that calls this function and then outputs all the information. This program is a miniature version of the ifconfig program and is shown in Figure 17.6.

Figure 17.6 prifinfo program that calls our get_ifi_info function.

ioctl/prifinfo.c

 1 #include     "unpifi.h"

 2 int
 3 main(int argc, char **argv)
 4 {
 5     struct ifi_info *ifi, *ifihead;
 6     struct sockaddr *sa;
 7     u_char *ptr;
 8     int     i, family, doaliases;
 9     if (argc != 3)
10         err_quit("usage: prifinfo <inet4|inet6> <doaliases>");
11     if (strcmp(argv[1], "inet4") == 0)
12         family = AF_INET;
13     else if (strcmp (argv[1], "inet6") == 0)
14         family = AF_INET6;
15     else
16         err_quit("invalid <address-family>");
17     doaliases = atoi(argv[2]);
18     for (ifihead = ifi = Get_ifi_info(family, doaliases);
19          ifi != NULL; ifi = ifi->ifi_next) {
20         printf("%s: ", ifi->ifi_name);
21         if (ifi->ifi_index != 0)
22             printf("(%d) ", ifi->ifi_index);
23         printf("<");
24         if (ifi->ifi_flags & IFF_UP)            printf("UP ");
25         if (ifi->ifi_flags & IFF_BROADCAST)     printf("BCAST ");
26         if (ifi->ifi_flags & IFF_MULTICAST)     printf("MCAST ");
27         if (ifi->ifi_flags & IFF_LOOPBACK)      printf("LOOP ");
28         if (ifi->ifi_flags & IFF_POINTOPOINT)   printf("P2P ");
29         printf(">\n");
30         if ( (i = ifi->ifi_hlen) > 0) {
31             ptr = ifi->ifi_haddr;
32             do {
33                 printf("%s%x", (i == ifi->ifi_hlen) ? "  " : ":", *ptr++);
34             } while (--i > 0);
35             printf("\n");
36         }
37         if (ifi->ifi_mtu != 0)
38             printf("  MTU: %d\n", ifi->ifi_mtu);
39         if ( (sa = ifi->ifi_addr) != NULL)
40             printf("  IP addr: %s\n", Sock_ntop_host (sa, sizeof (*sa)));
41         if ( (sa = ifi->ifi_brdaddr) != NULL)
42             printf("  broadcast addr: %s\n",
43                    Sock_ntop_host (sa, sizeof(*sa)));
44         if ( (sa = ifi->ifi_dstaddr) != NULL)
45             printf("  destination addr: %s\n",
46                    Sock_ntop_host(sa, sizeof(*sa)));
47     }
48     free_ifi_info(ifihead);
49     exit(0);
50 }

18–47 The program is a for loop that calls get_ifi_info once and then steps through all the ifi_info structures that are returned.

20–36 The interface name, index, and flags are all printed. If the length of the hardware address is greater than 0, it is printed as hexadecimal numbers. (Our get_ifi_info function returns an ifi_hlen of 0 if it is not available.)

37–46 The MTU and three IP addresses are printed, if returned.

If we run this program on our host macosx (Figure 1.16), we have the following output:


macosx % prifinfo inet4 0
lo0: <UP MCAST LOOP >
  MTU: 16384
  IP addr: 127.0.0.1
en1: <UP BCAST MCAST >
  MTU: 1500
  IP addr: 172.24.37.78
  broadcast addr: 172.24.37.95

The first command-line argument of inet4 specifies IPv4 addresses, and the second argument of 0 specifies that no address aliases are to be returned (we will describe IP address aliases in Section A.4). Note that under MacOS X, the hardware address of the Ethernet interface is not available using this method.

If we add three alias addresses to the Ethernet interface (en1) with host IDs of 79, 80, and 81, and if we change the second command-line argument to 1, we have the following:

macosx % prifinfo inet4 1
lo0: <UP MCAST LOOP >
  MTU: 16384
  IP addr: 127.0.0.1
 
en1: <UP BCAST MCAST >
  MTU: 1500
  IP addr: 172.24.37.78
  broadcast addr: 172.24.37.95

primary IP address

en1: <UP BCAST MCAST >
  MTU: 1500
  IP addr: 172.24.37.79
  broadcast addr: 172.24.37.95

first alias

en1: <UP BCAST MCAST >
  MTU: 1500
  IP addr: 172.24.37.80
  broadcast addr: 172.24.37.95

second alias

en1: <UP BCAST MCAST >
  MTU: 1500
  IP addr: 172.24.37.81
  broadcast addr: 172.24.37.95

third alias

If we run the same program under FreeBSD using the implementation of get_ifi_info from Figure 18.16 (which can easily obtain the hardware address), we have the following:

freebsd4 % prifinfo inet4 1
de0: <UP BCAST MCAST >
  0:80:c8:2b:d9:28
  IP addr: 135.197.17.100
  broadcast addr: 135.197.17.255
 
de1: <UP BCAST MCAST >
  0:40:5:42:d6:de
  IP addr: 172.24.37.94
  broadcast addr: 172.24.37.95

primary address

de1: <UP BCAST MCAST >
  0:40:5:42:d6:de
  IP addr: 172.24.37.93
  broadcast addr: 172.24.37.93

alias

lo0: <UP MCAST LOOP >
  IP addr: 127.0.0.1

For this example, we directed the program to print the aliases and we see that one alias is defined for the second Ethernet interface (de1) with a host ID of 93.

We now show our implementation of get_ifi_info that uses the SIOCGIFCONF ioctl. Figure 17.7 shows the first part of the function, which obtains the interface configuration from the kernel.

Figure 17.7 Issue SIOCGIFCONF request to obtain interface configuration.

lib/get_ifi_info.c

 1 #include     "unpifi.h"

 2 struct ifi_info *
 3 get_ifi_info(int family, int doaliases)
 4 {
 5     struct ifi_info *ifi, *ifihead, **ifipnext;
 6     int     sockfd, len, lastlen, flags, myflags, idx = 0, hlen = 0;
 7     char    *ptr, *buf, lastname[IFNAMSIZ], *cptr, *haddr, *sdlname;
 8     struct ifconf ifc;
 9     struct ifreq *ifr, ifrcopy;
10     struct sockaddr_in *sinptr;
11     struct sockaddr_in6 *sin6ptr;

12     sockfd = Socket(AF_INET, SOCK_DGRAM, 0);

13     lastlen = 0;
14     len = 100 * sizeof(struct ifreq);     /* initial buffer size guess */
15     for ( ; ; ) {
16         buf = Malloc(len);
17         ifc.ifc_len = len;
18         ifc.ifc_buf = buf;
19         if (ioctl(sockfd, SIOCGIFCONF, &ifc) < 0) {
20             if (errno != EINVAL || lastlen != 0)
21                 err_sys("ioctl error");
22         } else {
23             if (ifc.ifc_len == lastlen)
24                 break;          /* success, len has not changed */
25             lastlen = ifc.ifc_len;
26         }
27         len += 10 * sizeof(struct ifreq);     /* increment */
28         free(buf);
29     }
30     ifihead = NULL;
31     ifipnext = &ifihead;
32     lastname[0] = 0;
33     sdlname = NULL;

Create Internet Socket

11 We create a UDP socket that will be used with ioctls. Either a TCP or a UDP socket can be used (p. 163 of TCPv2).

Issue SIOCGIFCONF Request in a Loop

12–28 A fundamental problem with the SIOCGIFCONF request is that some implementations do not return an error if the buffer is not large enough to hold the result. Instead, the result is truncated and success is returned (a return value of 0 from ioctl). This means the only way we know that our buffer is large enough is to issue the request, save the return length, issue the request again with a larger buffer, and compare the length with the saved value. Only if the two lengths are the same is our buffer large enough.

Berkeley-derived implementations do not return an error if the buffer is too small (pp. 118–119 of TCPv2); the result is just truncated to fit the available buffer. Solaris 2.5, on the other hand, returns EINVAL if the returned length would be greater than or equal to the buffer length. But, we cannot assume success if the returned length is less than the buffer size because Berkeley-derived implementations can return less than the buffer size if another structure does not fit.

Some implementations provide a SIOCGIFNUM request that returns the number of interfaces. This allows the application to then allocate a buffer of sufficient size before issuing the SIOCGIFCONF request, but this new request is not widespread.

Allocating a fixed-sized buffer for the result from the SIOCGIFCONF request has become a problem with the growth of the Web, because large Web servers are allocating many alias addresses to a single interface. Solaris 2.5, for example, had a limit of 256 aliases per interface, but this limit increases to 8,192 with 2.6. Sites with numerous aliases discovered that programs with fixed-size buffers for interface information started failing. Even though Solaris returns an error if a buffer is too small, these programs allocate their fixed-size buffer, issue the ioctl, but then die if an error is returned.

12–15 We dynamically allocate a buffer, starting with room for 100 ifreq structures. We also keep track of the length returned by the last SIOCGIFCONF request in lastlen and initialize this to 0.

19–20 If an error of EINVAL is returned by ioctl, and we have not yet had a successful return (i.e., lastlen is still 0), we have not yet allocated a buffer large enough and continue through the loop.

22–23 If ioctl returns success, and if the returned length equals lastlen, the length has not changed (our buffer is large enough) and we break out of the loop since we have all the information.

26–27 Each time around the loop, we increase the buffer size to hold 10 more ifreq structures.

Initialize Linked List Pointers

29–31 Since we will be returning a pointer to the head of a linked list of ifi_info structures, we use the two variables ifihead and ifipnext to hold pointers to the list as we build it.

The next part of our get_ifi_info function, the beginning of the main loop, is shown in Figure 17.8.

Figure 17.8 Process interface configuration.

lib/get_ifi_info.c

34     for (ptr = buf; ptr < buf + ifc.ifc_len;) {
35          ifr = (struct ifreq *) ptr;

36 #ifdef   HAVE_SOCKADDR_SA_LEN
37          len = max(sizeof(struct sockaddr), ifr->ifr_addr.sa_len);
38 #else
39          switch (ifr->ifr_addr.sa_family) {
40 #ifdef   IPV6
41          case AF_INET6:
42              len = sizeof(struct sockaddr_in6);
43              break;
44 #endif
45          case AF_INET:
46          default:
47              len = sizeof(struct sockaddr);
48              break;
49          }
50 #endif   /* HAVE_SOCKADDR_SA_LEN */
51          ptr += sizeof(ifr->ifr_name) + len; /* for next one in buffer */

52 #ifdef   HAVE_SOCKADDR_DL_STRUCT
53          /* assumes that AF_LINK precedes AF_INET or AF_INET6 */
54          if (ifr->ifr_addr.sa_family == AF_LINK) {
55              struct sockaddr_dl *sdl = (struct sockaddr_dl *) &ifr->ifr_addr;
56              sdlname = ifr->ifr_name;
57              idx = sdl->sdl_index;
58              haddr = sdl->sdl_data + sdl->sdl_nlen;
59              hlen = sdl->sdl_alen;
60          }
61 #endif

62          if (ifr->ifr_addr.sa_family != family)
63              continue;              /* ignore if not desired address family */

64          myflags = 0;
65          if ( (cptr = strchr(ifr->ifr_name, ':')) != NULL)
66              *cptr = 0;          /* replace colon with null */
67          if (strncmp(lastname, ifr->ifr_name, IFNAMSIZ) == 0) {
68              if (doaliases == 0)
69                  continue;       /* already processed this interface */
70              myflags = IFI_ALIAS;
71          }
72          memcpy(lastname, ifr->ifr_name, IFNAMSIZ);

73          ifrcopy = *ifr;
74          Ioctl(sockfd, SIOCGIFFLAGS, &ifrcopy);
75          flags = ifrcopy.ifr_flags;
76          if ((flags & IFF_UP) == 0)
77              continue;               /* ignore if interface not up */

Step to Next Socket Address Structure

35–51 As we loop through all the ifreq structures, ifr points to each structure and we then increment ptr to point to the next one. But, we must deal with newer systems that provide a length field for socket address structures and older systems that do not provide this length. Even though the declaration in Figure 17.2 declares the socket address structure contained within the ifreq structure as a generic socket address structure, on newer systems, this can be any type of socket address structure. Indeed, on 4.4BSD, a datalink socket address structure is also returned for each interface (p. 118 of TCPv2). Therefore, if the length member is supported, we must use its value to update our pointer to the next socket address structure. Otherwise, we use a length based on the address family, using the size of the generic socket address structure (16 bytes) as the default.

We put in a case for IPv6, for newer systems, just in case. The problem is that the union in the ifreq structure defines the returned addresses as generic 16-byte sockaddr structures, which are adequate for 16-byte IPv4 sockaddr_in structures, but too small for 28-byte IPv6 sockaddr_in6 structures. This is not a problem on systems that have the sa_len field in the sockaddr since they can indicate variable-sized sockaddr structures easily.

Handle AF_LINK

52–60 If the system is one that returns AF_LINK sockaddrs in SIOCGIFCONF, copy the interface index and the hardware address information from the AF_LINK sockaddr.

62–63 We ignore any addresses from families except those desired by the caller.

Handle Aliases

64–72 We must detect any aliases that may exist for the interface, that is, additional addresses that have been assigned to the interface. Note from our examples following Figure 17.6 that under Solaris, the interface name for an alias contains a colon, while under 4.4BSD, the interface name does not change for an alias. To handle both cases, we save the last interface name in lastname and only compare up to a colon, if present. If a colon is not present, we still ignore this interface if the name is equivalent to the last interface we processed.

Fetch Interface Flags

73–77 We issue an ioctl of SIOCGIFFLAGS (Section 17.5) to fetch the interface flags. The third argument to ioctl is a pointer to an ifreq structure that must contain the name of the interface for which we want the flags. We make a copy of the ifreq structure before issuing the ioctl, because if we didn't, this request would overwrite the IP address of the interface since both are members of the same union in Figure 17.2. If the interface is not up, we ignore it.

Figure 17.9 contains the third part of our function.

Figure 17.9 Allocate and initialize ifi_info structure.

lib/get_ifi_info.c

78         ifi = Calloc(1, sizeof(struct ifi_info));
79         *ifipnext = ifi;        /* prev points to this new one */
80         ifipnext = &ifi->ifi_next;  /* pointer to next one goes here */

81         ifi->ifi_flags = flags; /* IFF_xxx values */
82         ifi->ifi_myflags = myflags; /* IFI_xxx values */
83 #if defined(SIOCGIFMTU) && defined(HAVE_STRUCT_IFREQ_IFR_MTU)
84         Ioctl(sockfd, SIOCGIFMTU, &ifrcopy);
85         ifi->ifi_mtu = ifrcopy.ifr_mtu;
86 #else
87         ifi->ifi_mtu = 0;
88 #endif
89         memcpy(ifi->ifi_name, ifr->ifr_name, IFI_NAME);
90         ifi->ifi_name [IFI_NAME - 1] = '\0';
91         /* If the sockaddr_dl is from a different interface, ignore it */
92         if (sdlname == NULL || strcmp (sdlname, ifr->ifr_name) != 0)
93             idx = hlen = 0;
94         ifi->ifi_index = idx;
95         ifi->ifi_hlen = hlen;
96         if (ifi->ifi_hlen > IFI_HADDR)
97             ifi->ifi_hlen = IFI_HADDR;
98         if (hlen)
99             memcpy(ifi->ifi_haddr, haddr, ifi->ifi_hlen);

Allocate and Initialize ifi_info Structure

78–99 At this point, we know that we will return this interface to the caller. We allocate memory for our ifi_info structure and add it to the end of the linked list we are building. We copy the interface flags, MTU, and name into the structure. We make certain that the interface name is null-terminated, and since calloc initializes the allocated region to all zero bits, we know that ifi_hlen is initialized to 0 and that ifi_next is initialized to a null pointer. We copy the saved interface index and hardware length; if the length is nonzero, we also copy the saved hardware address.

Figure 17.10 contains the last part of our function.

102–104 We copy the IP address that was returned from our original SIOCGIFCONF request in the structure we are building.

106–119 If the interface supports broadcasting, we fetch the broadcast address with an ioctl of SIOCGIFBRDADDR. We allocate memory for the socket address structure containing this address and add it to the ifi_info structure we are building. Similarly, if the interface is a point-to-point interface, the SIOCGIFDSTADDR returns the IP address of the other end of the link.

123–133 This is the IPv6 case; it is exactly the same as for IPv4 except that there is no call to SIOCGIFBRDADDR because IPv6 does not support broadcasting.

Figure 17.11 shows the free_ifi_info function, which takes a pointer that was returned by get_ifi_info and frees all the dynamic memory.

Figure 17.10 Fetch and return interface addresses.

lib/get_ifi_info.c

100        switch (ifr->ifr_addr.sa_family) {
101        case AF_INET:
102            sinptr = (struct sockaddr_in *) &ifr->ifr_addr;
103            ifi->ifi_addr = Calloc(1, sizeof(struct sockaddr_in));
104            memcpy(ifi->ifi_addr, sinptr, sizeof(struct sockaddr_in));

105 #ifdef SIOCGIFBRDADDR
106            if (flags & IFF_BROADCAST) {
107                Ioctl(sockfd, SIOCGIFBRDADDR, &ifrcopy);
108                sinptr = (struct sockaddr_in *) &ifrcopy.ifr_broadaddr;
109                ifi->ifi_brdaddr = Calloc(1, sizeof(struct sockaddr_in));
110                memcpy(ifi->ifi_brdaddr, sinptr, sizeof(struct sockaddr_in));
111            }
112 #endif

113 #ifdef SIOCGIFDSTADDR
114            if (flags & IFF_POINTOPOINT) {
115                Ioctl(sockfd, SIOCGIFDSTADDR, &ifrcopy);
116                sinptr = (struct sockaddr_in *) &ifrcopy.ifr_dstaddr;
117                ifi->ifi_dstaddr = Calloc(1, sizeof(struct sockaddr_in));
118                memcpy(ifi->ifi_dstaddr, sinptr, sizeof(struct sockaddr_in));
119            }
120 #endif
121            break;

122        case AF_INET6:
123            sin6ptr = (struct sockaddr_in6 *) &ifr->ifr_addr;
124            ifi->ifi_addr = Calloc(1, sizeof(struct sockaddr_in6));
125            memcpy(ifi->ifi_addr, sin6ptr, sizeof(struct sockaddr_in6));

126 #ifdef SIOCGIFDSTADDR
127            if (flags & IFF_POINTOPOINT) {
128                Ioctl(sockfd, SIOCGIFDSTADDR, &ifrcopy);
129                sin6ptr = (struct sockaddr_in6 *) &ifrcopy.ifr_dstaddr;
130                ifi->ifi_dstaddr = Calloc(1, sizeof(struct sockaddr_in6));
131                memcpy(ifi->ifi_dstaddr, sin6ptr,
132                       sizeof(struct sockaddr_in6));
133            }
134 #endif
135            break;

136        default:
137            break;
138        }
139    }
140    free(buf);
141    return (ifihead);           /* pointer to first structure in linked list */
142 }
Figure 17.11 free_ifi_info function: frees dynamic memory allocated by get_ifi_info.

lib/get_ifi_info.c

143 void
144 free_ifi_info(struct ifi_info *ifihead)
145 {
146     struct ifi_info *ifi, *ifinext;

147     for (ifi = ifihead; ifi != NULL; ifi = ifinext) {
148         if (ifi->ifi_addr != NULL)
149             free(ifi->ifi_addr);
150         if (ifi->ifi_brdaddr != NULL)
151             free(ifi->ifi_brdaddr);
152         if (ifi->ifi_dstaddr != NULL)
153             free(ifi->ifi_dstaddr);
154         ifinext = ifi->ifi_next;     /* can't fetch ifi_next after free() */
155         free(ifi);               /* the ifi_info{} itself */
156     }
157 }
    [ Team LiB ] Previous Section Next Section