The Sockets Networking API: UNIX® Network Programming Volume 1, Third Edition

Book description

UNIX Network Programming, Volume 1: The Sockets Networking API, Third Edition

"Everyone will want this book because it provides a great mix of practical experience, historical perspective, and a depth of understanding that only comes from being intimately involved in the field. I've already enjoyed and learned from reading this book, and surely you will too."

--Sam Leffler

The classic guide to UNIX networking APIs... now completely updated!

To build today's highly distributed, networked applications and services, you need deep mastery of sockets and other key networking APIs. One book delivers comprehensive, start-to-finish guidance for building robust, high-performance networked systems in any environment: UNIX Network Programming, Volume 1, Third Edition.

Building on the legendary work of W. Richard Stevens, this edition has been fully updated by two leading network programming experts to address today's most crucial standards, implementations, and techniques. New topics include:

  • POSIX Single UNIX Specification Version 3

  • IPv6 APIs (including updated guidance on IPv6/IPv4 interoperability)

  • The new SCTP transport protocol

  • IPsec-based Key Management Sockets

  • FreeBSD 4.8/5.1, Red Hat Linux 9.x, Solaris 9, AIX 5.x, HP-UX, and Mac OS X implementations

  • New network program debugging techniques

  • Source Specific Multicast API, the key enabler for widespread IP multicast deployment

  • The authors also update and extend Stevens' definitive coverage of these crucial UNIX networking standards and techniques:

  • TCP and UDP transport

  • Sockets: elementary, advanced, routed, and raw

  • I/O: multiplexing, advanced functions, nonblocking, and signal-driven

  • Daemons and inetd

  • UNIX domain protocols

  • ioctl operations

  • Broadcasting and multicasting

  • Threads

  • Streams

  • Design: TCP iterative, concurrent, preforked, and prethreaded servers

  • Since 1990, network programmers have turned to one source for the insights and techniques they need: W. Richard Stevens' UNIX Network Programming. Now, there's an edition specifically designed for today's challenges--and tomorrow's.

    Table of contents

    1. The Sockets Networking API
      1. Addison-Wesley Professional Computing Series
      2. Foreword
      3. Preface
        1. Introduction
        2. Changes from the Second Edition
        3. Using This Book
        4. Source Code and Errata Availability
        5. Acknowledgments
      4. 1. Introduction and TCP/IP
        1. 1. Introduction
            1. 1.1. Introduction
            2. 1.2. A Simple Daytime Client
              1. Include our own header
              2. Command-line arguments
              3. Create TCP socket
              4. Specify server’s IP address and port
              5. Establish connection with server
              6. Read and display server’s reply
              7. Terminate program
            3. 1.3. Protocol Independence
            4. 1.4. Error Handling: Wrapper Functions
              1. Unix errno Value
            5. 1.5. A Simple Daytime Server
              1. Create a TCP socket
              2. Bind server’s well-known port to socket
              3. Convert socket to listening socket
              4. Accept client connection, send reply
              5. Terminate connection
            6. 1.6. Roadmap to Client/Server Examples in the Text
            7. 1.7. OSI Model
            8. 1.8. BSD Networking History
            9. 1.9. Test Networks and Hosts
              1. Discovering Network Topology
            10. 1.10. Unix Standards
              1. Background on POSIX
              2. Background on The Open Group
              3. Unification of Standards
              4. Internet Engineering Task Force (IETF)
            11. 1.11. 64-Bit Architectures
            12. 1.12. Summary
            13. Exercises
        2. 2. The Transport Layer: TCP, UDP, and SCTP
            1. 2.1. Introduction
            2. 2.2. The Big Picture
            3. 2.3. User Datagram Protocol (UDP)
            4. 2.4. Transmission Control Protocol (TCP)
            5. 2.5. Stream Control Transmission Protocol (SCTP)
            6. 2.6. TCP Connection Establishment and Termination
              1. Three-Way Handshake
              2. TCP Options
              3. TCP Connection Termination
              4. TCP State Transition Diagram
              5. Watching the Packets
            7. 2.7. TIME_WAIT State
            8. 2.8. SCTP Association Establishment and Termination
              1. Four-Way Handshake
              2. Association Termination
              3. SCTP State Transition Diagram
              4. Watching the Packets
              5. SCTP Options
            9. 2.9. Port Numbers
              1. Socket Pair
            10. 2.10. TCP Port Numbers and Concurrent Servers
            11. 2.11. Buffer Sizes and Limitations
              1. TCP Output
              2. UDP Output
              3. SCTP Output
            12. 2.12. Standard Internet Services
            13. 2.13. Protocol Usage by Common Internet Applications
            14. 2.14. Summary
            15. Exercises
      5. 2. Elementary Sockets
        1. 3. Sockets Introduction
            1. 3.1. Introduction
            2. 3.2. Socket Address Structures
              1. IPv4 Socket Address Structure
              2. Generic Socket Address Structure
              3. IPv6 Socket Address Structure
              4. New Generic Socket Address Structure
              5. Comparison of Socket Address Structures
            3. 3.3. Value-Result Arguments
            4. 3.4. Byte Ordering Functions
            5. 3.5. Byte Manipulation Functions
            6. 3.6. inet_aton, inet_addr, and inet_ntoa Functions
            7. 3.7. inet_pton and inet_ntop Functions
              1. Example
            8. 3.8. sock_ntop and Related Functions
            9. 3.9. readn, writen, and readline Functions
            10. 3.10. Summary
            11. Exercises
        2. 4. Elementary TCP Sockets
            1. 4.1. Introduction
            2. 4.2. socket Function
              1. AF_xxx Versus PF_xxx
            3. 4.3. connect Function
            4. 4.4. bind Function
            5. 4.5. listen Function
            6. 4.6. accept Function
              1. Example: Value-Result Arguments
                1. New declarations
                2. Accept connection and print client’s address
            7. 4.7. fork and exec Functions
            8. 4.8. Concurrent Servers
            9. 4.9. close Function
              1. Descriptor Reference Counts
            10. 4.10. getsockname and getpeername Functions
              1. Example: Obtaining the Address Family of a Socket
                1. Allocate room for largest socket address structure
                2. Call getsockname
            11. 4.11. Summary
            12. Exercises
        3. 5. TCP Client/Server Example
            1. 5.1. Introduction
            2. 5.2. TCP Echo Server: main Function
              1. Create socket, bind server’s well-known port
              2. Wait for client connection to complete
              3. Concurrent server
            3. 5.3. TCP Echo Server: str_echo Function
              1. Read a buffer and echo the buffer
            4. 5.4. TCP Echo Client: main Function
              1. Create socket, fill in Internet socket address structure
              2. Connect to server
            5. 5.5. TCP Echo Client: str_cli Function
              1. Read a line, write to server
              2. Read echoed line from server, write to standard output
              3. Return to main
            6. 5.6. Normal Startup
            7. 5.7. Normal Termination
            8. 5.8. POSIX Signal Handling
              1. signal Function
                1. Simplify function prototype using typedef
                2. Set handler
                3. Set signal mask for handler
                4. Set SA_RESTART flag
                5. Call sigaction
              2. POSIX Signal Semantics
            9. 5.9. Handling SIGCHLD Signals
              1. Handling Zombies
              2. Handling Interrupted System Calls
            10. 5.10. wait and waitpid Functions
              1. Difference between wait and waitpid
            11. 5.11. Connection Abort before accept Returns
            12. 5.12. Termination of Server Process
            13. 5.13. SIGPIPE Signal
            14. 5.14. Crashing of Server Host
            15. 5.15. Crashing and Rebooting of Server Host
            16. 5.16. Shutdown of Server Host
            17. 5.17. Summary of TCP Example
            18. 5.18. Data Format
              1. Example: Passing Text Strings between Client and Server
              2. Example: Passing Binary Structures between Client and Server
            19. 5.19. Summary
            20. Exercises
        4. 6. I/O Multiplexing: The select and poll Functions
            1. 6.1. Introduction
            2. 6.2. I/O Models
              1. Blocking I/O Model
              2. Nonblocking I/O Model
              3. I/O Multiplexing Model
              4. Signal-Driven I/O Model
              5. Asynchronous I/O Model
              6. Comparison of the I/O Models
              7. Synchronous I/O versus Asynchronous I/O
            3. 6.3. select Function
              1. Under What Conditions Is a Descriptor Ready?
              2. Maximum Number of Descriptors for select
            4. 6.4. str_cli Function (Revisited)
              1. Call select
              2. Handle readable socket
              3. Handle readable input
            5. 6.5. Batch Input and Buffering
            6. 6.6. shutdown Function
            7. 6.7. str_cli Function (Revisited Again)
            8. 6.8. TCP Echo Server (Revisited)
              1. Create listening socket and initialize for select
              2. Block in select
              3. accept new connections
              4. Check existing connections
              5. Denial-of-Service Attacks
            9. 6.9. pselect Function
            10. 6.10. poll Function
            11. 6.11. TCP Echo Server (Revisited Again)
              1. Allocate array of pollfd structures
              2. Initialize
              3. Call poll, check for new connection
              4. Check for data on an existing connection
            12. 6.12. Summary
            13. Exercises
        5. 7. Socket Options
            1. 7.1. Introduction
            2. 7.2. getsockopt and setsockopt Functions
            3. 7.3. Checking if an Option Is Supported and Obtaining the Default
              1. Declare union of possible values
              2. Define function prototypes
              3. Define structure and initialize array
              4. Go through all options
              5. Create socket
              6. Call getsockopt
              7. Print option’s default value
            4. 7.4. Socket States
            5. 7.5. Generic Socket Options
              1. SO_BROADCAST Socket Option
              2. SO_DEBUG Socket Option
              3. SO_DONTROUTE Socket Option
              4. SO_ERROR Socket Option
              5. SO_KEEPALIVE Socket Option
              6. SO_LINGER Socket Option
              7. SO_OOBINLINE Socket Option
              8. SO_RCVBUF and SO_SNDBUF Socket Options
              9. SO_RCVLOWAT and SO_SNDLOWAT Socket Options
              10. SO_RCVTIMEO and SO_SNDTIMEO Socket Options
              11. SO_REUSEADDR and SO_REUSEPORT Socket Options
              12. SO_TYPE Socket Option
              13. SO_USELOOPBACK Socket Option
            6. 7.6. IPv4 Socket Options
              1. IP_HDRINCL Socket Option
              2. IP_OPTIONS Socket Option
              3. IP_RECVDSTADDR Socket Option
              4. IP_RECVIF Socket Option
              5. IP_TOS Socket Option
              6. IP_TTL Socket Option
            7. 7.7. ICMPv6 Socket Option
              1. ICMP6_FILTER Socket Option
            8. 7.8. IPv6 Socket Options
              1. IPV6_CHECKSUM Socket Option
              2. IPV6_DONTFRAG Socket Option
              3. IPV6_NEXTHOP Socket Option
              4. IPV6_PATHMTU Socket Option
              5. IPV6_RECVDSTOPTS Socket Option
              6. IPV6_RECVHOPLIMIT Socket Option
              7. IPV6_RECVHOPOPTS Socket Option
              8. IPV6_RECVPATHMTU Socket Option
              9. IPV6_RECVPKTINFO Socket Option
              10. IPV6_RECVRTHDR Socket Option
              11. IPV6_RECVTCLASS Socket Option
              12. IPV6_UNICAST_HOPS Socket Option
              13. IPV6_USE_MIN_MTU Socket Option
              14. IPV6_V6ONLY Socket Option
              15. IPV6_XXX Socket Options
            9. 7.9. TCP Socket Options
              1. TCP_MAXSEG Socket Option
              2. TCP_NODELAY Socket Option
            10. 7.10. SCTP Socket Options
              1. SCTP_ADAPTION_LAYER Socket Option
              2. SCTP_ASSOCINFO Socket Option
              3. SCTP_AUTOCLOSE Socket Option
              4. SCTP_DEFAULT_SEND_PARAM Socket Option
              5. SCTP_DISABLE_FRAGMENTS Socket Option
              6. SCTP_EVENTS Socket Option
              7. SCTP_GET_PEER_ADDR_INFO Socket Option
              8. SCTP_I_WANT_MAPPED_V4_ADDR Socket Option
              9. SCTP_INITMSG Socket Option
              10. SCTP_MAXBURST Socket Option
              11. SCTP_MAXSEG Socket Option
              12. SCTP_NODELAY Socket Option
              13. SCTP_PEER_ADDR_PARAMS Socket Option
              14. SCTP_PRIMARY_ADDR Socket Option
              15. SCTP_RTOINFO Socket Option
              16. SCTP_SET_PEER_PRIMARY_ADDR Socket Option
              17. SCTP_STATUS Socket Option
            11. 7.11. fcntl Function
            12. 7.12. Summary
            13. Exercises
        6. 8. Elementary UDP Sockets
            1. 8.1. Introduction
            2. 8.2. recvfrom and sendto Functions
            3. 8.3. UDP Echo Server: main Function
              1. Create UDP socket, bind server’s well-known port
            4. 8.4. UDP Echo Server: dg_echo Function
              1. Read datagram, echo back to sender
            5. 8.5. UDP Echo Client: main Function
              1. Fill in socket address structure with server’s address
            6. 8.6. UDP Echo Client: dg_cli Function
            7. 8.7. Lost Datagrams
            8. 8.8. Verifying Received Response
              1. Allocate another socket address structure
              2. Compare returned address
            9. 8.9. Server Not Running
            10. 8.10. Summary of UDP Example
            11. 8.11. connect Function with UDP
              1. Calling connect Multiple Times for a UDP Socket
              2. Performance
            12. 8.12. dg_cli Function (Revisited)
            13. 8.13. Lack of Flow Control with UDP
              1. UDP Socket Receive Buffer
            14. 8.14. Determining Outgoing Interface with UDP
            15. 8.15. TCP and UDP Echo Server Using select
              1. Create listening TCP socket
              2. Create UDP socket
                1. Establish signal handler for SIGCHLD
                2. Prepare for select
                3. Call select
                4. Handle new client connection
                5. Handle arrival of datagram
            16. 8.16. Summary
            17. Exercises
        7. 9. Elementary SCTP Sockets
            1. 9.1. Introduction
            2. 9.2. Interface Models
              1. The One-to-One Style
              2. The One-to-Many Style
            3. 9.3. sctp_bindx Function
            4. 9.4. sctp_connectx Function
            5. 9.5. sctp_getpaddrs Function
            6. 9.6. sctp_freepaddrs Function
            7. 9.7. sctp_getladdrs Function
            8. 9.8. sctp_freeladdrs Function
            9. 9.9. sctp_sendmsg Function
            10. 9.10. sctp_recvmsg Function
            11. 9.11. sctp_opt_info Function
            12. 9.12. sctp_peeloff Function
            13. 9.13. shutdown Function
            14. 9.14. Notifications
              1. SCTP_ASSOC_CHANGE
              2. SCTP_PEER_ADDR_CHANGE
              3. SCTP_REMOTE_ERROR
              4. SCTP_SEND_FAILED
              5. SCTP_SHUTDOWN_EVENT
              6. SCTP_ADAPTION_INDICATION
              7. SCTP_PARTIAL_DELIVERY_EVENT
            15. 9.15. Summary
            16. Exercises
        8. 10. SCTP Client/Server Example
            1. 10.1. Introduction
            2. 10.2. SCTP One-to-Many-Style Streaming Echo Server: main Function
              1. Set stream increment option
              2. Create an SCTP socket
              3. Bind an address
              4. Set up for notifications of interest
              5. Enable incoming associations
              6. Wait for message
              7. Increment stream number if desired
              8. Send back response
            3. 10.3. SCTP One-to-Many-Style Streaming Echo Client: main Function
              1. Validate arguments and create a socket
              2. Set up server address
              3. Set up for notifications of interest
              4. Call echo processing function
              5. Finish up
            4. 10.4. SCTP Streaming Echo Client: str_cli Function
              1. Initialize the sri structure and enter loop
              2. Validate input
              3. Translate stream number
              4. Send message
              5. Block while waiting for message
              6. Display returned message and loop
              7. Running the Code
            5. 10.5. Exploring Head-of-Line Blocking
              1. Initialize data structures and wait for input
              2. Pre-process message
              3. Send message to each stream
              4. Read back echoed messages and display
              5. Running the Code
                1. Add additional message number and send
                2. Change message number and send it again
                3. Read messages and display
              6. Running the Modified Code
            6. 10.6. Controlling the Number of Streams
              1. Initial setup
              2. Modifying the streams request
            7. 10.7. Controlling Termination
              1. Send back response, but shut down association
              2. Abort association before close
              3. Close socket descriptor
            8. 10.8. Summary
            9. Exercises
        9. 11. Name and Address Conversions
            1. 11.1. Introduction
            2. 11.2. Domain Name System (DNS)
              1. Resource Records
              2. Resolvers and Name Servers
              3. DNS Alternatives
            3. 11.3. gethostbyname Function
              1. Example
            4. 11.4. gethostbyaddr Function
            5. 11.5. getservbyname and getservbyport Functions
              1. Example: Using gethostbyname and getservbyname
                1. Call gethostbyname and getservbyname
                2. Try each server address
                3. Call connect
                4. Check for failure
                5. Read server’s reply
            6. 11.6. getaddrinfo Function
            7. 11.7. gai_strerror Function
            8. 11.8. freeaddrinfo Function
            9. 11.9. getaddrinfo Function: IPv6
            10. 11.10. getaddrinfo Function: Examples
            11. 11.11. host_serv Function
            12. 11.12. tcp_connect Function
              1. Call getaddrinfo
              2. Try each addrinfo structure until success or end of list
              3. Example: Daytime Client
                1. Command-line arguments
                2. Connect to server
                3. Print server’s address
            13. 11.13. tcp_listen Function
              1. Call getaddrinfo
              2. Create socket and bind address
              3. Check for failure
              4. Return size of socket address structure
              5. Example: Daytime Server
                1. Require service name or port number as command-line argument
                2. Create listening socket
                3. Server loop
              6. Example: Daytime Server with Protocol Specification
                1. Handle command-line arguments
            14. 11.14. udp_client Function
              1. Example: Protocol-Independent Daytime Client
            15. 11.15. udp_connect Function
            16. 11.16. udp_server Function
              1. Example: Protocol-Independent Daytime Server
            17. 11.17. getnameinfo Function
            18. 11.18. Re-entrant Functions
            19. 11.19. gethostbyname_r and gethostbyaddr_r Functions
            20. 11.20. Obsolete IPv6 Address Lookup Functions
              1. The RES_USE_INET6 Constant
              2. The gethostbyname2 Function
              3. The getipnodebyname Function
            21. 11.21. Other Networking Information
            22. 11.22. Summary
            23. Exercises
      6. 3. Advanced Sockets
        1. 12. IPv4 and IPv6 Interoperability
            1. 12.1. Introduction
            2. 12.2. IPv4 Client, IPv6 Server
            3. 12.3. IPv6 Client, IPv4 Server
              1. Summary of Interoperability
            4. 12.4. IPv6 Address-Testing Macros
            5. 12.5. Source Code Portability
            6. 12.6. Summary
            7. Exercises
        2. 13. Daemon Processes and the inetd Superserver
            1. 13.1. Introduction
            2. 13.2. syslogd Daemon
            3. 13.3. syslog Function
            4. 13.4. daemon_init Function
              1. fork
              2. setsid
              3. Ignore SIGHUP and Fork Again
              4. Set Flag for Error Functions
              5. Change Working Directory
              6. Close any open descriptors
              7. Redirect stdin, stdout, and stderr to /dev/null
              8. Use syslogd for Errors
              9. Example: Daytime Server as a Daemon
            5. 13.5. inetd Daemon
            6. 13.6. daemon_inetd Function
              1. Example: Daytime Server as a Daemon Invoked by inetd
                1. Call getpeername
            7. 13.7. Summary
            8. Exercises
        3. 14. Advanced I/O Functions
            1. 14.1. Introduction
            2. 14.2. Socket Timeouts
              1. connect with a Timeout Using SIGALRM
                1. Establish signal handler
                2. Set alarm
                3. Call connect
                4. Turn off alarm and restore any previous signal handler
                5. Handle SIGALRM
              2. recvfrom with a Timeout Using SIGALRM
                1. Handle timeout from recvfrom
                2. SIGALRM signal handler
              3. recvfrom with a Timeout Using select
                1. Prepare arguments for select
                2. Block in select
              4. recvfrom with a Timeout Using the SO_RCVTIMEO Socket Option
                1. Set socket option
                2. Test for timeout
            3. 14.3. recv and send Functions
            4. 14.4. readv and writev Functions
            5. 14.5. recvmsg and sendmsg Functions
            6. 14.6. Ancillary Data
            7. 14.7. How Much Data Is Queued?
            8. 14.8. Sockets and Standard I/O
              1. Example: str_echo Function Using Standard I/O
                1. Convert descriptor into input stream and output stream
            9. 14.9. Advanced Polling
              1. /dev/poll Interface
                1. List descriptors for /dev/poll
                2. Wait for work
                3. Loop through descriptors
              2. kqueue Interface
                1. Determine if file pointer points to a file
                2. Set up kevent structures for kqueue
                3. Create kqueue and add filters
                4. Loop forever, blocking in kevent
                5. Loop through returned events
                6. Socket is readable
                7. Input is readable
              3. Suggestions
            10. 14.10. Summary
            11. Exercises
        4. 15. Unix Domain Protocols
            1. 15.1. Introduction
            2. 15.2. Unix Domain Socket Address Structure
              1. Example: bind of Unix Domain Socket
                1. Remove pathname first
                2. bind and then getsockname
            3. 15.3. socketpair Function
            4. 15.4. Socket Functions
            5. 15.5. Unix Domain Stream Client/Server
            6. 15.6. Unix Domain Datagram Client/Server
            7. 15.7. Passing Descriptors
              1. Descriptor Passing Example
                1. Create stream pipe
                2. fork and exec
                3. Parent waits for child
                4. Receive descriptor
                5. Make certain msg_control is suitably aligned
                6. Command-line arguments
                7. open the file
                8. Pass back descriptor
            8. 15.8. Receiving Sender Credentials
              1. Example
            9. 15.9. Summary
            10. Exercises
        5. 16. Nonblocking I/O
            1. 16.1. Introduction
            2. 16.2. Nonblocking Reads and Writes: str_cli Function (Revisited)
              1. Set descriptors to nonblocking
              2. Initialize buffer pointers
              3. Main loop: prepare to call select
              4. Specify descriptors we are interested in
              5. Call select
              6. read from standard input
              7. Handle nonblocking error
              8. read returns EOF
              9. read returns data
              10. read from socket
              11. write to standard output
              12. write OK
              13. write to socket
              14. A Simpler Version of str_cli
              15. Timing of str_cli
            3. 16.3. Nonblocking connect
            4. 16.4. Nonblocking connect: Daytime Client
              1. Set socket nonblocking
              2. Overlap processing with connection establishment
              3. Check for immediate completion
              4. Call select
              5. Handle timeouts
              6. Check for readability or writability
              7. Turn off nonblocking and return
              8. Interrupted connect
            5. 16.5. Nonblocking connect: Web Client
              1. Define file structure
              2. Define globals and function prototypes
              3. Process command-line arguments
              4. Read home page
              5. Initialize globals
              6. Establish connection with server
              7. Send HTTP command to server, read reply
              8. Create socket, set to nonblocking
              9. Initiate nonblocking connect
              10. Handle connection complete
              11. Build command and send it
              12. Set flags
              13. Initiate another connection, if possible
              14. select: wait for something to happen
              15. Handle all ready descriptors
              16. See if descriptor has data
              17. Performance of Simultaneous Connections
            6. 16.6. Nonblocking accept
              1. Set SO_LINGER socket option
            7. 16.7. Summary
            8. Exercises
        6. 17. ioctl Operations
            1. 17.1. Introduction
            2. 17.2. ioctl Function
            3. 17.3. Socket Operations
            4. 17.4. File Operations
            5. 17.5. Interface Configuration
            6. 17.6. get_ifi_info Function
              1. Create Internet Socket
              2. Issue SIOCGIFCONF Request in a Loop
              3. Initialize Linked List Pointers
              4. Step to Next Socket Address Structure
              5. Handle AF_LINK
              6. Handle Aliases
              7. Fetch Interface Flags
              8. Allocate and Initialize ifi_info Structure
            7. 17.7. Interface Operations
            8. 17.8. ARP Cache Operations
              1. Example: Print Hardware Addresses of Host
                1. Get List of Addresses and Loop Through Each One
                2. Print IP Address
                3. Issue ioctl and Check for Error
                4. Print Hardware Address
            9. 17.9. Routing Table Operations
            10. 17.10. Summary
            11. Exercises
        7. 18. Routing Sockets
            1. 18.1. Introduction
            2. 18.2. Datalink Socket Address Structure
            3. 18.3. Reading and Writing
              1. Example: Fetch and Print a Routing Table Entry
                1. Create routing socket
                2. Fill in rt_msghdr structure
                3. Fill in Internet socket address structure with destination
                4. write message to kernel and read reply
                5. Loop through eight possible pointers
                6. Step to next socket address structure
            4. 18.4. sysctl Operations
              1. Example: Determine if UDP Checksums Are Enabled
                1. Include system headers
                2. Call sysctl
            5. 18.5. get_ifi_info Function (Revisited)
              1. Check if interface is up
              2. Determine which socket address structures are present
              3. Handle interface name
              4. Return IP addresses
              5. Return broadcast and destination addresses
            6. 18.6. Interface Name and Index Functions
              1. if_nametoindex Function
                1. Get interface list
                2. Process only RTM_IFINFO messages
              2. if_indextoname Function
              3. if_nameindex Function
                1. Get interface list, allocate room for result
                2. Process only RTM_IFINFO messages
                3. Terminate array
              4. if_freenameindex Function
            7. 18.7. Summary
            8. Exercises
        8. 19. Key Management Sockets
            1. 19.1. Introduction
            2. 19.2. Reading and Writing
            3. 19.3. Dumping the Security Association Database (SADB)
              1. Open PF_KEY socket
              2. Build SADB_DUMP request
              3. Display and write SADB_DUMP message
              4. Read replies
              5. Close PF_KEY socket
              6. Handle command-line arguments
              7. Call sadb_dump routine
              8. Sample Run
            4. 19.4. Creating a Static Security Association (SA)
              1. Open PF_KEY socket and save PID
              2. Build common message header
              3. Append SA extension
              4. Append source address
              5. Append destination address
              6. Append key
              7. Write message
              8. Read reply
              9. Example
            5. 19.5. Dynamically Maintaining SAs
              1. Open PF_KEY socket
              2. Store PID
              3. Create SADB_REGISTER message
              4. Display and write message to socket
              5. Wait for reply
              6. Example
            6. 19.6. Summary
            7. Exercises
        9. 20. Broadcasting
            1. 20.1. Introduction
            2. 20.2. Broadcast Addresses
            3. 20.3. Unicast versus Broadcast
            4. 20.4. dg_cli Function Using Broadcasting
              1. Allocate room for server’s address, set socket option
              2. Read line, send to socket, read all replies
              3. Print each received reply
              4. IP Fragmentation and Broadcasts
            5. 20.5. Race Conditions
              1. Blocking and Unblocking the Signal
                1. Declare signal set and initialize
                2. Unblock and block signal
              2. Blocking and Unblocking the Signal with pselect
              3. Using sigsetjmp and siglongjmp
                1. Allocate jump buffer
                2. Call sigsetjmp
                3. Handle SIGALRM and call siglongjmp
              4. Using IPC from Signal Handler to Function
                1. Create pipe
                2. select on both socket and read end of pipe
                3. read from pipe
            6. 20.6. Summary
            7. Exercises
        10. 21. Multicasting
            1. 21.1. Introduction
            2. 21.2. Multicast Addresses
              1. IPv4 Class D Addresses
              2. IPv6 Multicast Addresses
              3. Scope of Multicast Addresses
              4. Multicast Sessions
            3. 21.3. Multicasting versus Broadcasting on a LAN
            4. 21.4. Multicasting on a WAN
            5. 21.5. Source-Specific Multicast
            6. 21.6. Multicast Socket Options
              1. IP_ADD_MEMBERSHIP, IPV6_JOIN_GROUP, MCAST_JOIN_GROUP
              2. IP_DROP_MEMBERSHIP, IPV6_LEAVE_GROUP, MCAST_LEAVE_GROUP
              3. IP_BLOCK_SOURCE, MCAST_BLOCK_SOURCE
              4. IP_UNBLOCK_SOURCE, MCAST_UNBLOCK_SOURCE
              5. IP_ADD_SOURCE_MEMBERSHIP, MCAST_JOIN_SOURCE_GROUP
              6. IP_DROP_SOURCE_MEMBERSHIP, MCAST_LEAVE_SOURCE_GROUP
              7. IP_MULTICAST_IF, IPV6_MULTICAST_IF
              8. IP_MULTICAST_TTL, IPV6_MULTICAST_HOPS
              9. IP_MULTICAST_LOOP, IPV6_MULTICAST_LOOP
            7. 21.7. mcast_join and Related Functions
              1. Example: mcast_join Function
                1. Handle index
                2. Copy address and call setsockopt
                3. Handle index
                4. Handle name
                5. Specify default
                6. Copy address
                7. Handle index, name, or default
              2. Example: mcast_set_loop Function
            8. 21.8. dg_cli Function Using Multicasting
              1. IP Fragmentation and Multicasts
            9. 21.9. Receiving IP Multicast Infrastructure Session Announcements
              1. Well-Known name and Well-Known port
              2. Create UDP socket
              3. bind port
              4. Join multicast group
              5. Packet format
              6. Read UDP datagram, print sender and contents
              7. Check SAP header
              8. Find beginning of announcement and print
            10. 21.10. Sending and Receiving
              1. Create sending socket
              2. Create receiving socket and bind multicast address and port
              3. Join multicast group and turn off loopback
              4. fork and call appropriate functions
              5. Obtain hostname and form datagram contents
              6. Send datagram, then go to sleep
              7. Allocate socket address structure
              8. Read and print datagrams
              9. Example
            11. 21.11. Simple Network Time Protocol (SNTP)
              1. Get multicast IP address
              2. Bind wildcard address to socket
              3. Get interface list
              4. Join multicast group
              5. Read and process all NTP packets
              6. Validate packet
              7. Obtain transmit time from NTP packet
            12. 21.12. Summary
            13. Exercises
        11. 22. Advanced UDP Sockets
            1. 22.1. Introduction
            2. 22.2. Receiving Flags, Destination IP Address, and Interface Index
              1. Include files
              2. Function arguments
              3. Implemenation differences
              4. Fill in msghdr structure and call recvmsg
              5. Return if no control information
              6. Process ancillary data
              7. Process IP_RECVDSTADDR
              8. Process IP_RECVIF
              9. Example: Print Destination IP Address and Datagram-Truncated Flag
                1. Change MAXLINE
                2. Set IP_RECVDSTADDR and IP_RECVIF socket options
                3. Read datagram, print source IP address and port
                4. Print destination IP address
                5. Print name of received interface
                6. Test various flags
            3. 22.3. Datagram Truncation
            4. 22.4. When to Use UDP Instead of TCP
            5. 22.5. Adding Reliability to a UDP Application
              1. Example
                1. Define msghdr structures and hdr structure
                2. Initialize first time we are called
                3. Fill in msghdr structures
                4. Establish signal handler
                5. Send datagram
                6. Establish jump buffer
                7. Handle timeout
                8. Call recvmsg, compare sequence numbers
                9. Turn off alarm and update RTT estimators
                10. SIGALRM handler
                11. rtt_info structure
            6. 22.6. Binding Interface Addresses
              1. Call get_ifi_info, to obtain interface information
              2. Create UDP socket and bind unicast address
              3. fork child for this address
              4. Bind broadcast address
              5. fork child
              6. Create socket and bind wildcard address
              7. main function terminates
              8. New argument
              9. Read datagram and echo reply
            7. 22.7. Concurrent UDP Servers
            8. 22.8. IPv6 Packet Information
              1. Outgoing and Arriving Interface
              2. Source and Destination IPv6 Addresses
              3. Specifying and Receiving the Hop Limit
              4. Specifying the Next-Hop Address
              5. Specifying and Receiving the Traffic Class
            9. 22.9. IPv6 Path MTU Control
              1. Sending with Minimum MTU
              2. Receiving Path MTU Change Indications
              3. Determining the Current Path MTU
              4. Avoiding Fragmentation
            10. 22.10. Summary
            11. Exercises
        12. 23. Advanced SCTP Sockets
            1. 23.1. Introduction
            2. 23.2. An Autoclosing One-to-Many-Style Server
              1. Set autoclose option
            3. 23.3. Partial Delivery
              1. Prepare static buffer
              2. Read message
              3. Handle initial read error
              4. While there is more data for this message
              5. See if we need to grow static buffer
              6. Receive more data
              7. Move forward
              8. At loop end
              9. Read message
              10. Verify we read something
            4. 23.4. Notifications
              1. Cast and switch
              2. Process association change
              3. Peer address change
              4. Remote error
              5. Failed message
              6. Adaption layer indication
              7. Partial delivery notification
              8. Shutdown notification
              9. Set up to receive notifications
              10. Normal receive code
              11. Handle notification
              12. Running the Code
            5. 23.5. Unordered Data
              1. Send data using unordered service
            6. 23.6. Binding a Subset of Addresses
              1. Allocate space for bind arguments
              2. Process arguments
              3. Call binding function
              4. Return success
              5. Server code using IPv6
              6. Use the new sctp_bind_arg_list function
            7. 23.7. Determining Peer and Local Address Information
              1. Set events and call echo function
              2. Loop waiting for message
              3. Check for notifications
              4. Loop while waiting for data
              5. Display message
              6. Check if it is notification we want
              7. Gather and print peer addresses
              8. Gather and print local addresses
              9. Process each address
              10. Print address
              11. Determine address size
              12. Move address pointer
              13. Running the Code
            8. 23.8. Finding an Association ID Given an IP Address
              1. Initialize
              2. Copy address
              3. Call socket option
            9. 23.9. Heartbeating and Address Failure
              1. Zero sctp_paddrparams struct and copy interval
              2. Set up address
              3. Perform action
            10. 23.10. Peeling Off an Association
              1. Receive and process first message from client
              2. Translate address to association ID
              3. Extract association
              4. Delegate work to child
            11. 23.11. Controlling Timing
            12. 23.12. When to Use SCTP Instead of TCP
            13. 23.13. Summary
            14. Exercises
        13. 24. Out-of-Band Data
            1. 24.1. Introduction
            2. 24.2. TCP Out-of-Band Data
              1. Simple Example Using SIGURG
                1. Establish signal handler and socket owner
                2. SIGURG handler
              2. Simple Example Using select
            3. 24.3. sockatmark Function
              1. Example
                1. Set SO_OOBINLINE socket option
                2. sleep after connection accepted
                3. Read all data from sender
              2. Example
              3. Example
            4. 24.4. TCP Out-of-Band Data Recap
            5. 24.5. Summary
            6. Exercises
        14. 25. Signal-Driven I/O
            1. 25.1. Introduction
            2. 25.2. Signal-Driven I/O for Sockets
              1. SIGIO with UDP Sockets
              2. SIGIO with TCP Sockets
            3. 25.3. UDP Echo Server Using SIGIO
              1. Queue of received datagrams
              2. Array indexes
              3. Initialize queue of received datagrams
              4. Establish signal handlers and set socket flags
              5. Initialize signal sets
              6. Block SIGIO and wait for something to do
              7. Unblock SIGIO and send reply
              8. Block SIGIO
              9. Check for queue overflow
              10. Read datagram
              11. Increment counters and index
            4. 25.4. Summary
            5. Exercises
        15. 26. Threads
            1. 26.1. Introduction
            2. 26.2. Basic Thread Functions: Creation and Termination
              1. pthread_create Function
              2. pthread_join Function
              3. pthread_self Function
              4. pthread_detach Function
              5. pthread_exit Function
            3. 26.3. str_cli Function Using Threads
              1. unpthread.h header
              2. Save arguments in externals
              3. Create new thread
              4. Main thread loop: copy socket to standard output
              5. Terminate
              6. copyto thread
            4. 26.4. TCP Echo Server Using Threads
              1. Create thread
              2. Thread function
              3. Passing Arguments to New Threads
              4. Thread-Safe Functions
            5. 26.5. Thread-Specific Data
              1. Example: readline Function Using Thread-Specific Data
                1. Destructor
                2. One-time function
                3. Rline structure
                4. my_read function
                5. Allocate thread-specific data
                6. Fetch thread-specific data pointer
            6. 26.6. Web Client and Simultaneous Connections (Continued)
              1. Globals
              2. If possible, create another thread
              3. Wait for any thread to terminate
              4. Create TCP socket, establish connection
              5. Write request to server
              6. Read server’s reply
            7. 26.7. Mutexes: Mutual Exclusion
            8. 26.8. Condition Variables
            9. 26.9. Web Client and Simultaneous Connections (Continued)
              1. If possible, create another thread
              2. Wait for thread to terminate
              3. Handle terminated thread
            10. 26.10. Summary
            11. Exercises
        16. 27. IP Options
            1. 27.1. Introduction
            2. 27.2. IPv4 Options
            3. 27.3. IPv4 Source Route Options
              1. Initialize
              2. Argument
              3. Check for overflow
              4. Obtain binary IP address and store in route
              5. Save first IP address, skip any NOPs
              6. Check for source route option
              7. Example
                1. Process command-line arguments
                2. Handle destination address and create socket
              8. Deleting Received Source Route
            4. 27.4. IPv6 Extension Headers
            5. 27.5. IPv6 Hop-by-Hop Options and Destination Options
            6. 27.6. IPv6 Routing Header
              1. Create source route
              2. Look up destination and create socket
              3. Set sticky IPV6_RTHDR option and call worker function
              4. Turn on IPV6_RECVRTHDR option and set up msghdr struct
              5. Set up modifiable fields and call recvmsg
              6. Find and process route header
              7. Echo packet
              8. Determine number of segments in route
              9. Loop through each segment
            7. 27.7. IPv6 Sticky Options
            8. 27.8. Historical IPv6 Advanced API
            9. 27.9. Summary
            10. Exercises
        17. 28. Raw Sockets
            1. 28.1. Introduction
            2. 28.2. Raw Socket Creation
            3. 28.3. Raw Socket Output
              1. IPv6 Differences
              2. IPV6_CHECKSUM Socket Option
            4. 28.4. Raw Socket Input
              1. ICMPv6 Type Filtering
            5. 28.5. ping Program
              1. Include IPv4 and ICMPv4 headers
              2. Define proto structure
              3. Include IPv6 and ICMPv6 headers
              4. Define proto structures for IPv4 and IPv6
              5. Length of optional data
              6. Handle command-line options
              7. Process hostname argument
              8. Create socket
              9. Perform protocol-specific initialization
              10. Set socket receive buffer size
              11. Send first packet
              12. Set up msghdr for recvmsg
              13. Infinite loop reading all ICMP messages
              14. Get pointer to ICMP header
              15. Check for ICMP echo reply
              16. Print all received ICMP messages if verbose option specified
              17. Set ICMPv6 receive filter
              18. Request IPV6_HOPLIMIT ancillary data
              19. Get pointer to ICMPv6 header
              20. Check for ICMP echo reply
              21. Print all received ICMP messages if verbose option specified
              22. Build ICMPv4 message
              23. Calculate ICMP checksum
              24. Send datagram
              25. Internet checksum algorithm
            6. 28.6. traceroute Program
              1. Define proto structure
              2. Include IPv6 headers
              3. Define proto structures
              4. Set defaults
              5. Process command-line arguments
              6. Process hostname or IP address argument and finish initialization
              7. Create raw socket
              8. Set ICMPv6 receive filter
              9. Create UDP socket and bind source port
              10. Establish signal handler for SIGALRM
              11. Main loop; set TTL or hop limit and send three probes
              12. Set destination port and send UDP datagram
              13. Read ICMP message
              14. Print reply
              15. Set alarm and read each ICMP message
              16. Get pointer to ICMP header
              17. Process ICMP “time exceeded in transit” message
              18. Process ICMP “port unreachable” message
              19. Handle other ICMP messages
              20. Example
            7. 28.7. An ICMP Message Daemon
              1. UDP Echo Client That Uses Our icmpd Daemon
                1. bind wildcard address and ephemeral port
                2. Establish Unix domain connection to daemon
                3. Send UDP socket to daemon, await daemon’s reply
                4. Call select
                5. Print server’s reply
                6. Handle ICMP error
              2. UDP Echo Client Examples
              3. icmpd Daemon
                1. client array
                2. Initialize client array
                3. Create sockets
                4. Check listening Unix domain socket
                5. Check raw ICMP sockets
                6. Check connected Unix domain sockets
                7. Read client data and possibly a descriptor
                8. Get port number bound to UDP socket
                9. Indicate success to client
                10. close client’s UDP socket
                11. Handle errors and termination of client
                12. Check message type, notify application
                13. Check for UDP error, find client
                14. Build icmpd_err structure
            8. 28.8. Summary
            9. Exercises
        18. 29. Datalink Access
            1. 29.1. Introduction
            2. 29.2. BSD Packet Filter (BPF)
            3. 29.3. Datalink Provider Interface (DLPI)
            4. 29.4. Linux: SOCK_PACKET and PF_PACKET
            5. 29.5. libpcap: Packet Capture Library
            6. 29.6. libnet: Packet Creation and Injection Library
            7. 29.7. Examining the UDP Checksum Field
              1. Process command-line options
              2. Process destination name and port
              3. Process local name and port
              4. Create raw socket and open packet capture device
              5. Change permissions and establish signal handlers
              6. Perform test and cleanup
              7. Choose packet capture device
              8. Open device
              9. Obtain network address and subnet mask
              10. Compile packet filter
              11. Load filter program
              12. Determine datalink type
              13. volatile variables
              14. Establish signal handler and jump buffer
              15. Handle siglongjmp
              16. Send DNS query and read reply
              17. Examine received UDP checksum
              18. Allocate buffer and initialize pointer
              19. Build DNS query
              20. Write UDP datagram
              21. Declare raw socket descriptor
              22. Create raw socket and enable IP_HDRINCL
              23. Initialize packet header pointers
              24. Zero header
              25. Update lengths
              26. Fill in UDP header and calculate UDP checksum
              27. Fill in IP header
              28. Fetch and print packet capture statistics
              29. Example
              30. libnet Output Functions
                1. Declare libnet descriptor
                2. Initialize libnet
                3. Build DNS query
                4. Fill in UDP header and arrange for UDP checksum calculation
                5. Fill in IP header
                6. Write UDP datagram
            8. 29.8. Summary
            9. Exercises
        19. 30. Client/Server Design Alternatives
            1. 30.1. Introduction
            2. 30.2. TCP Client Alternatives
            3. 30.3. TCP Test Client
            4. 30.4. TCP Iterative Server
            5. 30.5. TCP Concurrent Server, One Child per Client
            6. 30.6. TCP Preforked Server, No Locking Around accept
              1. 4.4BSD Implementation
              2. Effect of Too Many Children
              3. Distribution of Connections to the Children
              4. select Collisions
            7. 30.7. TCP Preforked Server, File Locking Around accept
              1. Effect of Too Many Children
              2. Distribution of Connections to the Children
            8. 30.8. TCP Preforked Server, Thread Locking Around accept
            9. 30.9. TCP Preforked Server, Descriptor Passing
              1. Turn off listening socket if no available children
              2. accept new connection
              3. Handle any newly available children
              4. Wait for descriptor from parent
              5. Tell parent we are ready
            10. 30.10. TCP Concurrent Server, One Thread per Client
              1. Main thread loop
              2. Per-thread function
            11. 30.11. TCP Prethreaded Server, per-Thread accept
              1. Create thread
            12. 30.12. TCP Prethreaded Server, Main Thread accept
              1. Define shared array to hold connected sockets
              2. Create pool of threads
              3. Wait for each client connection
              4. Wait for client descriptor to service
            13. 30.13. Summary
            14. Exercises
        20. 31. Streams
            1. 31.1. Introduction
            2. 31.2. Overview
              1. Message Types
            3. 31.3. getmsg and putmsg Functions
            4. 31.4. getpmsg and putpmsg Functions
            5. 31.5. ioctl Function
            6. 31.6. Transport Provider Interface (TPI)
              1. Open transport provider, bind local address
              2. Fill in server’s address, establish connection
              3. Read data from server, copy to standard output
              4. Fill in T_bind_req structure
              5. Call putmsg
              6. Call getmsg to read high-priority message
              7. Process reply
              8. Fill in request structure and send to provider
              9. Read response
              10. Wait for connection to be established
              11. Read control and data; process reply
              12. Send orderly release to peer
            7. 31.7. Summary
            8. Exercises
      7. A. IPv4, IPv6, ICMPv4, and ICMPv6
        1. A.1. Introduction
        2. A.2. IPv4 Header
        3. A.3. IPv6 Header
        4. A.4. IPv4 Addresses
          1. Subnet Addresses
          2. Loopback Addresses
          3. Unspecified Address
          4. Private Addresses
          5. Multihoming and Address Aliases
        5. A.5. IPv6 Addresses
          1. Global Unicast Addresses
          2. 6 bone Test Addresses
          3. IPv4-Mapped IPv6 Addresses
          4. IPv4-Compatible IPv6 Addresses
          5. Loopback Address
          6. Unspecified Address
          7. Link-Local Address
          8. Site-Local Address
        6. A.6. Internet Control Message Protocols (ICMPv4 and ICMPv6)
      8. B. Virtual Networks
        1. B.1. Introduction
        2. B.2. The MBone
        3. B.3. The 6bone
        4. B.4. IPv6 Transition: 6to4
      9. C. Debugging Techniques
        1. C.1. System Call Tracing
          1. BSD Kernel Sockets
          2. Solaris 9 Kernel Sockets
        2. C.2. Standard Internet Services
        3. C.3. sock Program
        4. C.4. Small Test Programs
        5. C.5. tcpdump Program
        6. C.6. netstat Program
        7. C.7. lsof Program
      10. D. Miscellaneous Source Code
        1. D.1. unp.h Header
        2. D.2. config.h Header
        3. D.3. Standard Error Functions
      11. E. Solutions to Selected Exercises
        1. Chapter 1
        2. Chapter 2
        3. Chapter 3
        4. Chapter 4
        5. Chapter 5
        6. Chapter 6
        7. Chapter 7
        8. Chapter 8
        9. Chapter 9
        10. Chapter 10
        11. Chapter 11
        12. Chapter 12
        13. Chapter 13
        14. Chapter 14
        15. Chapter 15
        16. Chapter 16
        17. Chapter 17
        18. Chapter 18
        19. Chapter 20
        20. Chapter 21
        21. Chapter 22
        22. Chapter 24
        23. Chapter 25
        24. Chapter 26
        25. Chapter 27
        26. Chapter 28
        27. Chapter 29
        28. Chapter 30
        29. Chapter 31
      12. Bibliography

    Product information

    • Title: The Sockets Networking API: UNIX® Network Programming Volume 1, Third Edition
    • Author(s):
    • Release date: November 2003
    • Publisher(s): Addison-Wesley Professional
    • ISBN: 0131411551