Home
小杰的博客 Prev Page Prev Page
?
Main Page
Table of content
Copyright
Addison-Wesley Professional Computing Series
Foreword
Preface
Introduction
Changes from the Second Edition
Using This Book
Source Code and Errata Availability
Acknowledgments
Part 1: Introduction and TCP/IP
Chapter 1. Introduction
1.1 Introduction
1.2 A Simple Daytime Client
1.3 Protocol Independence
1.4 Error Handling: Wrapper Functions
1.5 A Simple Daytime Server
1.6 Roadmap to Client/Server Examples in the Text
1.7 OSI Model
1.8 BSD Networking History
1.9 Test Networks and Hosts
1.10 Unix Standards
1.11 64-Bit Architectures
1.12 Summary
Exercises
Chapter 2. The Transport Layer: TCP, UDP, and SCTP
2.1 Introduction
2.2 The Big Picture
2.3 User Datagram Protocol (UDP)
2.4 Transmission Control Protocol (TCP)
2.5 Stream Control Transmission Protocol (SCTP)
2.6 TCP Connection Establishment and Termination
2.7 TIME_WAIT State
2.8 SCTP Association Establishment and Termination
2.9 Port Numbers
2.10 TCP Port Numbers and Concurrent Servers
2.11 Buffer Sizes and Limitations
2.12 Standard Internet Services
2.13 Protocol Usage by Common Internet Applications
2.14 Summary
Exercises
Part 2: Elementary Sockets
Chapter 3. Sockets Introduction
3.1 Introduction
3.2 Socket Address Structures
3.3 Value-Result Arguments
3.4 Byte Ordering Functions
3.5 Byte Manipulation Functions
3.6 'inet_aton', 'inet_addr', and 'inet_ntoa' Functions
3.7 'inet_pton' and 'inet_ntop' Functions
3.8 'sock_ntop' and Related Functions
3.9 'readn', 'writen', and 'readline' Functions
3.10 Summary
Exercises
Chapter 4. Elementary TCP Sockets
4.1 Introduction
4.2 'socket' Function
4.3 'connect' Function
4.4 'bind' Function
4.5 'listen' Function
4.6 'accept' Function
4.7 'fork' and 'exec' Functions
4.8 Concurrent Servers
4.9 'close' Function
4.10 'getsockname' and 'getpeername' Functions
4.11 Summary
Exercises
Chapter 5. TCP Client/Server Example
5.1 Introduction
5.2 TCP Echo Server: 'main' Function
5.3 TCP Echo Server: 'str_echo' Function
5.4 TCP Echo Client: 'main' Function
5.5 TCP Echo Client: 'str_cli' Function
5.6 Normal Startup
5.7 Normal Termination
5.8 POSIX Signal Handling
5.9 Handling 'SIGCHLD' Signals
5.10 'wait' and 'waitpid' Functions
5.11 Connection Abort before 'accept' Returns
5.12 Termination of Server Process
5.13 'SIGPIPE' Signal
5.14 Crashing of Server Host
5.15 Crashing and Rebooting of Server Host
5.16 Shutdown of Server Host
5.17 Summary of TCP Example
5.18 Data Format
5.19 Summary
Exercises
Chapter 6. I/O Multiplexing: The 'select' and 'poll' Functions
6.1 Introduction
6.2 I/O Models
6.3 'select' Function
6.4 'str_cli' Function (Revisited)
6.5 Batch Input and Buffering
6.6 'shutdown' Function
6.7 'str_cli' Function (Revisited Again)
6.8 TCP Echo Server (Revisited)
6.9 'pselect' Function
6.10 'poll' Function
6.11 TCP Echo Server (Revisited Again)
6.12 Summary
Exercises
Chapter 7. Socket Options
7.1 Introduction
7.2 'getsockopt' and 'setsockopt' Functions
7.3 Checking if an Option Is Supported and Obtaining the Default
7.4 Socket States
7.5 Generic Socket Options
7.6 IPv4 Socket Options
7.7 ICMPv6 Socket Option
7.8 IPv6 Socket Options
7.9 TCP Socket Options
7.10 SCTP Socket Options
7.11 'fcntl' Function
7.12 Summary
Exercises
Chapter 8. Elementary UDP Sockets
8.1 Introduction
8.2 'recvfrom' and 'sendto' Functions
8.3 UDP Echo Server: 'main' Function
8.4 UDP Echo Server: 'dg_echo' Function
8.5 UDP Echo Client: 'main' Function
8.6 UDP Echo Client: 'dg_cli' Function
8.7 Lost Datagrams
8.8 Verifying Received Response
8.9 Server Not Running
8.10 Summary of UDP Example
8.11 'connect' Function with UDP
8.12 'dg_cli' Function (Revisited)
8.13 Lack of Flow Control with UDP
8.14 Determining Outgoing Interface with UDP
8.15 TCP and UDP Echo Server Using 'select'
8.16 Summary
Exercises
Chapter 9. Elementary SCTP Sockets
9.1 Introduction
9.2 Interface Models
9.3 'sctp_bindx' Function
9.4 'sctp_connectx' Function
9.5 'sctp_getpaddrs' Function
9.6 'sctp_freepaddrs' Function
9.7 'sctp_getladdrs' Function
9.8 'sctp_freeladdrs' Function
9.9 'sctp_sendmsg' Function
9.10 'sctp_recvmsg' Function
9.11 'sctp_opt_info' Function
9.12 'sctp_peeloff' Function
9.13 'shutdown' Function
9.14 Notifications
9.15 Summary
Exercises
Chapter 10. SCTP Client/Server Example
10.1 Introduction
10.2 SCTP One-to-Many-Style Streaming Echo Server: 'main' Function
10.3 SCTP One-to-Many-Style Streaming Echo Client: 'main' Function
10.4 SCTP Streaming Echo Client: 'str_cli' Function
10.5 Exploring Head-of-Line Blocking
10.6 Controlling the Number of Streams
10.7 Controlling Termination
10.8 Summary
Exercises
Chapter 11. Name and Address Conversions
11.1 Introduction
11.2 Domain Name System (DNS)
11.3 'gethostbyname' Function
11.4 'gethostbyaddr' Function
11.5 'getservbyname' and 'getservbyport' Functions
11.6 'getaddrinfo' Function
11.7 'gai_strerror' Function
11.8 'freeaddrinfo' Function
11.9 'getaddrinfo' Function: IPv6
11.10 'getaddrinfo' Function: Examples
11.11 'host_serv' Function
11.12 'tcp_connect' Function
11.13 'tcp_listen' Function
11.14 'udp_client' Function
11.15 'udp_connect' Function
11.16 'udp_server' Function
11.17 'getnameinfo' Function
11.18 Re-entrant Functions
11.19 'gethostbyname_r' and 'gethostbyaddr_r' Functions
11.20 Obsolete IPv6 Address Lookup Functions
11.21 Other Networking Information
11.22 Summary
Exercises
Part 3: Advanced Sockets
Chapter 12. IPv4 and IPv6 Interoperability
12.1 Introduction
12.2 IPv4 Client, IPv6 Server
12.3 IPv6 Client, IPv4 Server
12.4 IPv6 Address-Testing Macros
12.5 Source Code Portability
12.6 Summary
Exercises
Chapter 13. Daemon Processes and the 'inetd' Superserver
13.1 Introduction
13.2 'syslogd' Daemon
13.3 'syslog' Function
13.4 'daemon_init' Function
13.5 'inetd' Daemon
13.6 'daemon_inetd' Function
13.7 Summary
Exercises
Chapter 14. Advanced I/O Functions
14.1 Introduction
14.2 Socket Timeouts
14.3 'recv' and 'send' Functions
14.4 'readv' and 'writev' Functions
14.5 'recvmsg' and 'sendmsg' Functions
14.6 Ancillary Data
14.7 How Much Data Is Queued?
14.8 Sockets and Standard I/O
14.9 Advanced Polling
14.10 Summary
Exercises
Chapter 15. Unix Domain Protocols
15.1 Introduction
15.2 Unix Domain Socket Address Structure
15.3 'socketpair' Function
15.4 Socket Functions
15.5 Unix Domain Stream Client/Server
15.6 Unix Domain Datagram Client/Server
15.7 Passing Descriptors
15.8 Receiving Sender Credentials
15.9 Summary
Exercises
Chapter 16. Nonblocking I/O
16.1 Introduction
16.2 Nonblocking Reads and Writes: 'str_cli' Function (Revisited)
16.3 Nonblocking 'connect'
16.4 Nonblocking 'connect:' Daytime Client
16.5 Nonblocking 'connect:' Web Client
16.6 Nonblocking 'accept'
16.7 Summary
Exercises
Chapter 17. 'ioctl' Operations
17.1 Introduction
17.2 'ioctl' Function
17.3 Socket Operations
17.4 File Operations
17.5 Interface Configuration
17.6 'get_ifi_info' Function
17.7 Interface Operations
17.8 ARP Cache Operations
17.9 Routing Table Operations
17.10 Summary
Exercises
Chapter 18. Routing Sockets
18.1 Introduction
18.2 Datalink Socket Address Structure
18.3 Reading and Writing
18.4 'sysctl' Operations
18.5 'get_ifi_info' Function (Revisited)
18.6 Interface Name and Index Functions
18.7 Summary
Exercises
Chapter 19. Key Management Sockets
19.1 Introduction
19.2 Reading and Writing
19.3 Dumping the Security Association Database (SADB)
19.4 Creating a Static Security Association (SA)
19.5 Dynamically Maintaining SAs
19.6 Summary
Exercises
Chapter 20. Broadcasting
20.1 Introduction
20.2 Broadcast Addresses
20.3 Unicast versus Broadcast
20.4 'dg_cli' Function Using Broadcasting
20.5 Race Conditions
20.6 Summary
Exercises
Chapter 21. Multicasting
21.1 Introduction
21.2 Multicast Addresses
21.3 Multicasting versus Broadcasting on a LAN
21.4 Multicasting on a WAN
21.5 Source-Specific Multicast
21.6 Multicast Socket Options
21.7 'mcast_join' and Related Functions
21.8 'dg_cli' Function Using Multicasting
21.9 Receiving IP Multicast Infrastructure Session Announcements
21.10 Sending and Receiving
21.11 Simple Network Time Protocol (SNTP)
21.12 Summary
Exercises
Chapter 22. Advanced UDP Sockets
22.1 Introduction
22.2 Receiving Flags, Destination IP Address, and Interface Index
22.3 Datagram Truncation
22.4 When to Use UDP Instead of TCP
22.5 Adding Reliability to a UDP Application
22.6 Binding Interface Addresses
22.7 Concurrent UDP Servers
22.8 IPv6 Packet Information
22.9 IPv6 Path MTU Control
22.10 Summary
Exercises
Chapter 23. Advanced SCTP Sockets
23.1 Introduction
23.2 An Autoclosing One-to-Many-Style Server
23.3 Partial Delivery
23.4 Notifications
23.5 Unordered Data
23.6 Binding a Subset of Addresses
23.7 Determining Peer and Local Address Information
23.8 Finding an Association ID Given an IP Address
23.9 Heartbeating and Address Failure
23.10 Peeling Off an Association
23.11 Controlling Timing
23.12 When to Use SCTP Instead of TCP
23.13 Summary
Exercises
Chapter 24. Out-of-Band Data
24.1 Introduction
24.2 TCP Out-of-Band Data
24.3 'sockatmark' Function
24.4 TCP Out-of-Band Data Recap
24.5 Summary
Exercises
Chapter 25. Signal-Driven I/O
25.1 Introduction
25.2 Signal-Driven I/O for Sockets
25.3 UDP Echo Server Using 'SIGIO'
25.4 Summary
Exercises
Chapter 26. Threads
26.1 Introduction
26.2 Basic Thread Functions: Creation and Termination
26.3 'str_cli' Function Using Threads
26.4 TCP Echo Server Using Threads
26.5 Thread-Specific Data
26.6 Web Client and Simultaneous Connections (Continued)
26.7 Mutexes: Mutual Exclusion
26.8 Condition Variables
26.9 Web Client and Simultaneous Connections (Continued)
26.10 Summary
Exercises
Chapter 27. IP Options
27.1 Introduction
27.2 IPv4 Options
27.3 IPv4 Source Route Options
27.4 IPv6 Extension Headers
27.5 IPv6 Hop-by-Hop Options and Destination Options
27.6 IPv6 Routing Header
27.7 IPv6 Sticky Options
27.8 Historical IPv6 Advanced API
27.9 Summary
Exercises
Chapter 28. Raw Sockets
28.1 Introduction
28.2 Raw Socket Creation
28.3 Raw Socket Output
28.4 Raw Socket Input
28.5 'ping' Program
28.6 'traceroute' Program
28.7 An ICMP Message Daemon
28.8 Summary
Exercises
Chapter 29. Datalink Access
29.1 Introduction
29.2 BSD Packet Filter (BPF)
29.3 Datalink Provider Interface (DLPI)
29.4 Linux: 'SOCK_PACKET' and 'PF_PACKET'
29.5 'libpcap': Packet Capture Library
29.6 'libnet': Packet Creation and Injection Library
29.7 Examining the UDP Checksum Field
29.8 Summary
Exercises
Chapter 30. Client/Server Design Alternatives
30.1 Introduction
30.2 TCP Client Alternatives
30.3 TCP Test Client
30.4 TCP Iterative Server
30.5 TCP Concurrent Server, One Child per Client
30.6 TCP Preforked Server, No Locking Around 'accept'
30.7 TCP Preforked Server, File Locking Around 'accept'
30.8 TCP Preforked Server, Thread Locking Around 'accept'
30.9 TCP Preforked Server, Descriptor Passing
30.10 TCP Concurrent Server, One Thread per Client
30.11 TCP Prethreaded Server, per-Thread 'accept'
30.12 TCP Prethreaded Server, Main Thread 'accept'
30.13 Summary
Exercises
Chapter 31. Streams
31.1 Introduction
31.2 Overview
31.3 'getmsg' and 'putmsg' Functions
31.4 'getpmsg' and 'putpmsg' Functions
31.5 'ioctl' Function
31.6 Transport Provider Interface (TPI)
31.7 Summary
Exercises
Appendix A. IPv4, IPv6, ICMPv4, and ICMPv6
A.1 Introduction
A.2 IPv4 Header
A.3 IPv6 Header
A.4 IPv4 Addresses
A.5 IPv6 Addresses
A.6 Internet Control Message Protocols (ICMPv4 and ICMPv6)
Appendix B. Virtual Networks
B.1 Introduction
B.2 The MBone
B.3 The 6bone
B.4 IPv6 Transition: 6to4
Appendix C. Debugging Techniques
C.1 System Call Tracing
C.2 Standard Internet Services
C.3 'sock' Program
C.4 Small Test Programs
C.5 'tcpdump' Program
C.6 'netstat' Program
C.7 'lsof' Program
Appendix D. Miscellaneous Source Code
D.1 'unp.h' Header
D.2 'config.h' Header
D.3 Standard Error Functions
Appendix E. Solutions to Selected Exercises
Chapter 1
Chapter 2
Chapter 3
Chapter 4
Chapter 5
Chapter 6
Chapter 7
Chapter 8
Chapter 9
Chapter 10
Chapter 11
Chapter 12
Chapter 13
Chapter 14
Chapter 15
Chapter 16
Chapter 17
Chapter 18
Chapter 20
Chapter 21
Chapter 22
Chapter 24
Chapter 25
Chapter 26
Chapter 27
Chapter 28
Chapter 29
Chapter 30
Chapter 31
Bibliography
?
[ 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鈥?1 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鈥?7 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鈥?6 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鈥?6 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鈥?8 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鈥?19 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鈥?5 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鈥?0 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鈥?3 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鈥?7 Each time around the loop, we increase the buffer size to hold 10 more ifreq structures.

Initialize Linked List Pointers

29鈥?1 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鈥?1 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鈥?0 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鈥?3 We ignore any addresses from families except those desired by the caller.

Handle Aliases

64鈥?2 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鈥?7 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鈥?9 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鈥?04 We copy the IP address that was returned from our original SIOCGIFCONF request in the structure we are building.

106鈥?19 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鈥?33 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
Converted from CHM to HTML with chm2web Pro 2.85 (unicode)