Learning notes of Chapter 13 of Unix/Linux system programming

Learning notes of Chapter 13 of Unix/Linux system programming

Summary of knowledge points

This chapter discusses TCP/IP and network programming, which is divided into two parts. The first part discusses TCP/IP protocol and its application, including TCP/IP stack, IP address, host name, DNS, IP packet and router; This paper introduces UDP and TCP protocol, port number and data flow in TCP/IP network; The server client computing model and socket programming interface are described; Network programming is demonstrated by using examples of UDP and TCP sockets. The first programming project can implement a pair of TCP server clients that perform file operations through the Internet, allowing users to define other communication protocols to reliably transmit file content.
The second part of this chapter introduces Web and CGI programming, and explains HTTP programming model, Web page and Web browser; It shows how to configure Linux HTTPD server to support user Web page, PHP and CGI programming; The dynamic Web pages of client and server are explained; Demonstrates how to create server-side dynamic Web pages using PHP and CGI.

TCP/IP protocol

  • Literally, some people may think that TCP/IP refers to TCP and IP protocols. In real life, it sometimes refers to these two agreements. However, in many cases, it is only the general name of the protocol group that must be used when using IP for communication. Specifically, IP or ICMP, TCP or UDP, TELNET or FTP, and HTTP all belong to TCP/IP protocols. They are closely related to TCP or IP and are an essential part of the Internet. The term TCP/IP generally refers to these protocols. Therefore, TCP/IP is sometimes called Internet protocol group.
  • When communicating with the Internet, corresponding network protocols are required. TCP/IP is originally a protocol family developed for the use of the Internet. Therefore, the protocol of the Internet is TCP/IP, and TCP/IP is the protocol of the Internet.

IP host and IP address

The IP address is divided into two parts: networkID field and HostID field. According to the division, IP addresses are divided into A~E categories. For example, a class B IP address is divided into a 16 bit networkID, where the first two bits are 10, and then a 16 bit HostID field. Packets destined for IP addresses are first sent to routers with the same networkID. The router will forward the packet to a specific host in the network through the HostID. Each host has a local host name localhost, and the default IP address is The link layer of the local host is a loopback virtual device, which routes each packet back to the same localhost. This feature allows us to run TCP/IP applications on the same computer without actually connecting to the Internet.

IP protocol

IP protocol is used to send / receive packets between IP hosts. IP works best. The IP host only sends packets to the receiving host, but it can not guarantee that the packets will be sent to their destination or in order. This means that IP is not a reliable protocol. If necessary, reliability must be realized above the IP layer.


UDP (User Datagram Protocol) (RFC768 1980;Comer 1988) runs over IP for sending / receiving datagrams. Similar to IP, UDP does not guarantee reliability, but it is fast and efficient. It can be used in situations where reliability is not important.

TCP (transmission control protocol) is a connection oriented protocol used to send / receive data streams. TCP can also run over IP, but it ensures reliable data transmission. Generally, UDP is similar to USPS sending mail, while TCP is similar to telephone connection.

Port number

Application = (host IP, protocol, port number)
The protocol is TCP or UDP, and the port number is the only unsigned short integer assigned to the application. To use UDP or TCP, an application (process) must first select or obtain a port number. The first 1024 port numbers have been reserved. Other port numbers are available for general use. The application can select an available port number or let the operating system kernel assign a port number.

Socket programming

(1) Socket address

struct sockaddr_in {
sa_family_t sin_family; // AF_INET for TCP/IP
// port number
in_port_t sin_port;
struct in_addr sin_addr;// IP address );
// internet address struct in_addr {
// IP address in network byte order

(2) Socket API

The server must create a socket and bind it to the socket address containing the server IP address and port number. It can use a fixed port number or let the operating system kernel choose a port number (if sin port is 0). In order to communicate with the server, the client must create a socket. For UPD sockets, you can bind the socket to the server address. If the socket is not bound to any specific server, it must provide a socket address containing the server IP and port number in subsequent sendto() / recvfrom() calls.


#include <stdio.h>
#include <arpa/inet.h>//inet_addr() sockaddr_in
#include <string.h>//bzero()
#include <sys/socket.h>//socket
#include <unistd.h>
#include <stdlib.h>//exit()

#define BUFFER_SIZE 1024

int main() {

    char listen_addr_str[] = "";
    size_t listen_addr = inet_addr(listen_addr_str);
    int port = 8080;
    int server_socket, client_socket;
    struct sockaddr_in server_addr, client_addr;
    socklen_t addr_size;
    char buffer[BUFFER_SIZE];//Buffer size
    int str_length;
    server_socket = socket(PF_INET, SOCK_STREAM, 0);//Create socket
    bzero(&server_addr, sizeof(server_addr));//initialization
    server_addr.sin_family = INADDR_ANY;
    server_addr.sin_port = htons(port);
    server_addr.sin_addr.s_addr = listen_addr;
    if (bind(server_socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) == -1) {
        printf("Binding failed\n");



    if (listen(server_socket, 5) == -1) {

        printf("Listening failed\n");



    printf("establish tcp Server success\n");



    fd_set reads,copy_reads;

    int fd_max,fd_num;

    struct timeval timeout;


    FD_ZERO(&reads);//Initialize and empty socket collection





    while (1) {

        copy_reads = reads;

        timeout.tv_sec = 5;

        timeout.tv_usec = 5000;


        //Infinite loop call select to monitor readable events

        if((fd_num = select(fd_max+1, &copy_reads, 0, 0, &timeout)) == -1) {

            perror("select error");



        if (fd_num==0){//socket without change




        for(int i=0;i<fd_max+1;i++){


                if (i==server_socket){//server_socket changes, representing a new client connection

                    addr_size = sizeof(client_addr);

                    client_socket = accept(server_socket, (struct sockaddr *) &client_addr, &addr_size);

                    printf("%d Connection succeeded\n", client_socket);

                    char msg[] = "Congratulations on your successful connection";

                    write(client_socket, msg, sizeof(msg));


                    if(fd_max < client_socket){




                    memset(buffer, 0, sizeof(buffer));

                    str_length = read(i, buffer, BUFFER_SIZE);

                    if (str_length == 0)    //Close socket after reading data



                        printf("The connection has been closed: %d \n", i);

                        FD_CLR(i, &reads);//Delete relevant information from reads

                    } else {

                        printf("%d Client sends data:%s \n", i, buffer);

                        write(i, buffer, str_length);//Send data back to client








    return 0;


Posted on Sun, 28 Nov 2021 06:54:54 -0500 by PHPBewildered