【Linux】Network communication

【Linux】Network communication

1. Network foundation

1.1 Computer network

The development of computer networks can gradually evolve from an independent model to a network interconnection model. This process can be divided into the following stages:

  1. Standalone mode :
    In the early days of computer networking, each computer was a relatively independent entity, not connected to other computers. Each computer is used only for a separate task, with very limited sharing of data and resources. In this stage, computers are mainly used for scientific computing and data processing.

  2. Peer-to-peer connections :
    As the number of computers increased, people began to realize that connecting computers together allowed for more efficient resource sharing and communication. Thus, the network model of point-to-point connection emerged, in which two computers are directly connected through a dedicated communication line, allowing data transmission. This mode is more common in the early LAN.

  3. Rise of Local Area Networks (LANs) :
    As the number of computers further increased, Local Area Networks (LANs) began to rise. A LAN allows computers located in the same geographic location to be connected to each other for resource sharing and communication. The development of Ethernet technology allowed computers to communicate over a shared physical medium (like a single cable), thus enabling local area networks.

  4. Emergence of Wide Area Networks (WAN) :
    With the development of computer networks, people want to be able to communicate across a large geographical area. The Wide Area Network (WAN) emerged to interconnect computers over a larger area by connecting multiple local area networks and point-to-point connections. This network mode uses routers and switches to transmit data between different networks.

  5. Rise of the Internet :
    The Internet is the highest stage in the development of computer networks. It connects computer networks around the world to realize seamless data exchange and resource sharing. The Internet uses the TCP/IP protocol suite as the communication basis, allowing different types of networks and devices to communicate with each other, thus forming a global information exchange platform.

1.2 Network Model

A computer network model is an abstract framework used to describe the relationship and communication between various components in a computer network. Common computer network models are as follows:

  1. OSI Model (Open Systems Interconnection Model) :
    The OSI model is a seven-layer network model formulated by the International Organization for Standardization (ISO), each layer representing a specific network function. From bottom to top are the physical layer, data link layer, network layer, transport layer, session layer, presentation layer and application layer. The main goal of this model is to facilitate communication between devices developed by different vendors. In practice, however, most networks use the TCP/IP model mentioned below.

  2. TCP/IP model :
    The TCP/IP model is actually used on the Internet, and it consists of four layers: network interface layer, network layer, transport layer and application layer. Although fewer layers, it contains similar functions as those in the OSI model. The name of this model comes from its two core protocols: Transmission Control Protocol (TCP) and Internet Protocol (IP).

  3. Four-layer network model :
    There are some network models that divide the network into four layers: physical layer, data link layer, network layer, and application layer. This model omits the session layer, presentation layer and transport layer, which simplifies the structure of the network.

  4. Five-layer network model :
    This model divides the network into five layers: physical layer, data link layer, network layer, transport layer, and application layer. It is similar in function to the TCP/IP model, but contains only five layers.

image-20230810113050172

TCP/IP is a synonym for a group of protocols, and it also includes many protocols, which form the TCP/IP protocol cluster. The TCP/IP protocol cluster is divided into four layers, IP is located in the second layer of the protocol cluster (corresponding to the third layer of OSI), and TCP is located in the third layer of the protocol cluster (corresponding to the fourth layer of OSI). The TCP/IP communication protocol adopts a 4-layer hierarchical structure, and each layer calls the network provided by its next layer to fulfill its own needs. The 4 layers are:

  • Application layer : The layer for communication between applications, such as Simple Email Transfer (SMTP), File Transfer Protocol (FTP), Network Remote Access Protocol (Telnet), etc.
  • Transport layer : In this layer, it provides data transmission services between nodes, such as Transmission Control Protocol (TCP), User Datagram Protocol (UDP), etc., TCP and UDP add transmission data to the data packet and transmit it to the next In one layer, this layer is responsible for transmitting data and making sure that data has been delivered and received.
  • Network interconnection layer : Responsible for providing basic data packet transmission functions, so that each piece of data packet can reach the destination host (but does not check whether it is received correctly), such as Internet Protocol (IP).
  • Host to network layer : manage the actual network media, define how to use the actual network (such as Ethernet, Serial Line, etc.) to transmit data.

TCP & UDP

1) IP address

img

2) port

1. Used to distinguish different applications

2. The range of the port number is 0-65535, among which 0-1023 is not a system reserved port, our program should not use these ports as much as possible!

3. The IP address and port number make up our Socket, which is the endpoint of the two-way communication link between network running programs, and is the basis of TCP and UDP!

4. Ports used by common protocols: HTTP: 80, FTP: 21, TELNET: 23

img

3) Comparison of TCP protocol and UDP protocol

Detailed TCP protocol process :

First of all, TCP/IP is a protocol cluster, which includes many protocols. UDP is just one of them. The reason why it is named TCP/IP protocol is because TCP and IP protocol are two very important protocols, so they are named after them.

Let's explain the difference between the TCP protocol and the UDP protocol:

TCP (Transmission Control Protocol, Transmission Control Protocol) is a connection-oriented protocol, that is, when sending and receiving data money, it is necessary to establish a reliable link with the opposite party. This is also the three-way handshake of TCP and the four-way handshake of TCP that are often asked in interviews ! Three-way handshake : When establishing a TCP connection, the client and the server need to send a total of 3 packets to confirm the establishment of the connection. In Socket programming, this process is triggered by the client executing connect. The specific flow chart is as follows:

img

  • The first handshake : the client sets the flag bit SYN to 1, randomly generates a value seq=J, and sends the data packet to the server, the client enters the SYN_SENT state, and waits for the server to confirm.
  • The second handshake : After the server receives the data packet, the flag bit SYN=1 knows that the client requests to establish a connection, the server sets the flag bits SYN and ACK to 1, ack=J+1, randomly generates a value seq=K, and Send the data packet to the Client to confirm the connection request, and the Server enters the SYN_RCVD state.
  • The third handshake : After receiving the confirmation, the Client checks whether the ack is J+1 and whether the ACK is 1. If it is correct, the flag bit ACK is set to 1, ack=K+1, and the data packet is sent to the Server. The server checks whether the ack is K+1 and whether the ACK is 1. If it is correct, the connection is successfully established. The client and the server enter the ESTABLISHED state to complete the three-way handshake, and then the client and the server can start transmitting data.
  • Wave four times : Terminate the TCP connection, which means that when disconnecting a TCP connection, the client and the server need to send a total of 4 packets to confirm the disconnection of the connection. In Socket programming, this process is triggered by either the client or the server executing close. The specific flow chart is as follows:

img

  • First wave : Client sends a FIN to close the data transmission from Client to Server, and Client enters FIN_WAIT_1 state
  • The second wave : After receiving the FIN, the Server sends an ACK to the Client, confirming that the sequence number is the received sequence number + 1 (same as SYN, one FIN occupies one sequence number), and the Server enters the CLOSE_WAIT state.
  • The third wave : the server sends a FIN to close the data transmission from the server to the client, and the server enters the LAST_ACK state.
  • The fourth wave : After the Client receives the FIN, the Client enters the TIME_WAIT state, and then sends an ACK to the Server, confirming that the serial number is the received serial number + 1, and the Server enters the CLOSED state, and completes four waved hands. In addition, it may also be the case that an active shutdown is initiated at the same time:

img

In addition, there may be a common question: why is it a three-way handshake to establish a connection, but four waves to close the connection? Answer: Because the server is in the LISTEN state, after receiving the SYN message of the connection establishment request, it puts the ACK and SYN in one message and sends it to the client. When closing the connection, when receiving the other party's FIN message, it only means that the other party no longer sends data but can still receive data, and one's own party may not have sent all the data to the other party, so one's own party can close immediately, or send some After the data is sent to the other party, send a FIN message to the other party to express agreement to close the connection now. Therefore, your own ACK and FIN are generally sent separately.


Detailed explanation of UDP protocol :

UDP (User Datagram Protocol) User Datagram Protocol, a non-connection protocol, the source and the terminal do not establish a connection before transmitting data. When it wants to transmit, it simply grabs the data from the application and sends it as quickly as possible. It is thrown on the network. At the sending end, the speed at which UDP transmits data is only limited by the speed at which the application generates data, the capabilities of the computer, and the transmission bandwidth; Read a message segment. Compared with TCP, there is no need to establish a link, the structure is simple, the correctness cannot be guaranteed, and it is easy to lose packets

1.3 Network transmission

There is a close relationship between network transmission and network models. The network model provides a structured framework and guidelines for network transmission, helping to understand and organize the data transmission process in the network.

The TCP/IP protocol cluster is a set of protocols, which includes five layers: physical layer, data link layer, network layer, transport layer and application layer. Each layer has specific functions and tasks:

  1. Physical layer : responsible for transmitting optical/electrical signals, including Ethernet, optical fiber, wireless network, etc. Hubs work at this layer.

  2. Data link layer : transmit and identify data frames, handle frame synchronization, collision detection, and data error checking. Switches work at this layer.

  3. Network layer : perform address management and routing selection, identify hosts through IP addresses, and plan data transmission paths. Routers work at this layer.

  4. Transport layer : Responsible for data transmission between hosts, such as the TCP protocol to ensure reliable data transmission.

  5. Application Layer : Handles communication between applications, such as email transfer (SMTP), file transfer (FTP), remote access (Telnet), etc.

The five-layer structure works together to form the TCP/IP protocol cluster, which supports various communication and data transmission functions of modern computer networks.

For a host, its operating system kernel implements the content from the transport layer to the physical layer

For a router, it implements from the network layer to the physical layer

For a switch, it implements from the data link layer to the physical layer

For hubs, it only implements the physical layer

1.3.1 Transmission logic

The logic of data transmission can be summarized as follows:

  1. Preparation stage :

    • At the application layer, the data to be transmitted is prepared, the data format and processing logic are defined.
    • Select an appropriate application layer protocol, such as HTTP, FTP, etc., to determine the data transmission method and rules.
  2. Transport layer protocol selection :

    • Select the transport layer protocol according to the application requirements. If the reliability requirement is high, choose TCP, and if the real-time requirement is high, choose UDP.
  3. Establish a connection and listen :

    • For TCP, it is necessary to establish a connection. A connection is established between the sender and the receiver to ensure reliable data transmission.
    • For UDP, a connection is not required, but it is necessary to determine the destination address for data sending and receiving.
  4. Data encapsulation and header information :

    • At the sending end, encapsulate the application layer data into packets, and add appropriate transport layer and network layer header information.
    • The header information includes IP address, port number, etc., and is used for routing and identification of target devices.
  5. Data transfer :

    • The transport layer protocol is responsible for transmitting the encapsulated data packets to the target device, while performing operations such as error detection and flow control.
    • The network layer protocol selects an appropriate route according to the target IP address to determine the transmission path of the data packet.
  6. Physical transport :

    • The link layer encapsulates the data packet into a frame, adds the link layer header and tail, and transmits it to the receiving end through the physical medium.
  7. Data unpacking and processing :

    • At the receiving end, the link layer receives and parses the frame, and passes the data to the network layer.
    • The network layer determines the target device according to the IP address, and hands the data to the transport layer.
  8. Data reorganization and parsing :

    • The transport layer protocol is responsible for reassembling the received data packets in order, performing error detection and correction, and delivering the data to the application layer.
  9. Application layer processing :

    • The application parses the data packet, processes the data content according to the defined data format, and executes the corresponding business logic.

This logical process covers all stages and processes of data transmission from the application layer to the physical layer, ensuring that data can be transmitted and processed according to certain rules and procedures.

1.3.2 Transmission conditions

The prerequisites for data transmission are classified according to the application layer, transport layer, network layer and link layer as follows:

Application layer :

  1. Communication equipment : At least two communication equipment are required.
  2. IP address and port number : Each device requires a unique IP address and appropriate port number.
  3. Data format definition : The format of the data needs to be defined so that the sender and receiver can correctly parse and process the data.
  4. Security considerations : Data security and encryption need to be considered, especially for the transmission of sensitive information.

transport layer :

  1. Protocol selection : It is necessary to select an appropriate transport layer protocol, such as TCP or UDP, according to the data transmission requirements.
  2. Transport mechanism : You need to understand how to establish a connection, transfer data, manage traffic, and close connections.
  3. Error handling mechanism : It is necessary to consider possible errors in data transmission, such as packet loss and retransmission.

Network layer :

  1. Network connection : Communication devices need to be connected together through a network, which can be wired or wireless.
  2. IP address : Each device needs a unique IP address, which is used to identify the device in the network.
  3. Routing : It is necessary to use routing protocols to select the transmission path of data packets.

link layer :

  1. Physical connection : Communication devices need to be connected through physical level, such as Ethernet, radio waves, etc.
  2. Link address : The link layer needs to determine the physical address of each device, such as the MAC address.

1.3.3 Transmission process

When sending emails in daily life, the specific process of TCP/IP protocol transmission is shown in the following table:

step level Actions and headers
1 application layer Write emails and prepare email content.
2 application layer Use an email client.
3 application layer Encapsulate mail data.
4 transport layer Select the TCP protocol.
5 transport layer Establish a TCP connection.
6 transport layer Encapsulate mail data into TCP packets.
7 Network layer Select an IP address.
8 Network layer Encapsulates TCP packets into IP packets.
9 link layer Framing and adding link layer headers.
10 link layer Transfer data over physical media.
11 link layer Parse the data frame and remove the link layer header.
12 Network layer Analyze the IP data packet to obtain the target IP.
13 transport layer TCP reassembles and checks packets.
14 transport layer Pass the packet to the application layer.
15 application layer Parse email data and process email content.
16 application layer Continue processing mail, possibly forwarding.

1.4 Address Management

Network addresses exist to identify different devices and hosts in a computer network. Different levels of network models need to use network addresses to determine the sender and receiver of data during data transmission.

  • Physical layer : The physical layer is responsible for signal transmission, but in order to ensure that the signal reaches the correct device, each device needs to have a unique physical address in the network, which is the MAC address. This is an address used in the data link layer to identify a device on a local area network.

  • Data Link Layer : At the data link layer, data frames need to carry a destination MAC address and a source MAC address so that the device can send and receive data correctly. These addresses are used to identify devices within a local area network.

  • Network layer : At the network layer, IP addresses are used to identify different hosts and routers. IP addresses are used to find targeted devices globally, enabling data to be transmitted across different networks.

  • Transport layer : At the transport layer, data contains source and destination port numbers. Together, these port numbers form a socket that identifies different applications and services. They help the transport layer deliver data to the correct application.

In conclusion, addresses play a key role in different network layers, used to identify different devices, hosts and services. They help ensure that data travels correctly across the network and enable communications to proceed smoothly.

2. Network programming

2.1 Basic concepts

2.1.1 IP address

An IP address (Internet Protocol Address) is a digital label used to uniquely identify and locate a device in a computer network. It is part of the Internet protocol suite and is used for the routing and delivery of data packets in the network. IP addresses act like mailing addresses to ensure that data is delivered accurately from sender to recipient.

The following are the basic concepts of IP addresses:

  1. Unique identification: Each device (such as computer, server, router, mobile device, etc.) is assigned a unique IP address in the network. This helps ensure that packets are routed and delivered correctly.

  2. Hierarchical structure: IP addresses are usually divided into two main versions: IPv4 (Internet Protocol version 4) and IPv6 (Internet Protocol version 6). IPv4 is represented using 32-bit binary numbers, usually presented in dotted decimal notation (for example, 192.168.1.1). IPv6 is represented using 128-bit binary numbers, displayed in a more complex manner (for example, 2001:0db8:85a3:0000:0000:8a2e:0370:7334).

  3. IPv4 address exhaustion: Due to the rapid expansion of the Internet, the IPv4 address space has been largely exhausted. This led to the introduction of IPv6 as it provides a larger address space capable of supporting more connected devices in the future.

  4. Public and private addresses: IP addresses can be public or private. Public IP addresses are unique globally and are used for direct access to the internet. Private IP addresses are used within a local area network (such as a home or business intranet) and are not directly exposed to the Internet.

  5. Subnet Mask: A subnet mask is a parameter used in conjunction with an IP address to indicate which parts are network parts and which parts are host parts. It helps divide IP addresses into networks and hosts for more efficient routing within subnets.

  6. DHCP and Static IP: IP addresses can be assigned automatically via Dynamic Host Configuration Protocol (DHCP), or manually configured as static IP addresses. DHCP allows network devices to automatically obtain IP addresses and other network configuration information when they join a network.

  7. Network layer address: IP address is located in the network layer (layer 3) protocol, which is responsible for the transmission of data packets from the source host to the destination host. It works with the MAC address (at the data link layer, layer 2) to transfer data between different networks.

IP addresses are the basis of Internet communication, through which data can be transmitted accurately and reliably around the world. Whether browsing the web, sending emails or making video calls, IP addresses play a vital role behind the scenes.

Relationship with agreement

The IP address is a key concept in the Internet protocol suite, and it cooperates with multiple other protocols to realize the transmission and communication of data in the network. Here's how IP addresses relate to some other important protocols:

  1. TCP/IP Protocol Stack: TCP/IP is a set of network protocols that together form the basis of the Internet. The IP address is a core component in the TCP/IP protocol stack. TCP (Transmission Control Protocol) is responsible for establishing a reliable connection and data transmission between the two communicating parties, while IP is responsible for routing data packets from the source host to the destination host.

  2. MAC address: MAC address (Media Access Control Address) is an identifier of the data link layer (layer 2), which is used to uniquely identify network devices in a local area network. The IP address (located in the network layer, the third layer) cooperates with the MAC address, and through mechanisms such as ARP (Address Resolution Protocol), the IP address is mapped to the corresponding MAC address to realize data transmission in the LAN.

  3. ARP protocol: ARP (Address Resolution Protocol) is used to resolve an IP address into a corresponding MAC address. When a device needs to send data to another device, it needs to know the MAC address of the target device. The ARP protocol helps the host find the MAC address corresponding to the IP address in the same LAN.

  4. DHCP protocol: DHCP (Dynamic Host Configuration Protocol) is used to automatically assign IP addresses and other network configuration information to new devices that join the network. The DHCP server assigns an available IP address to the client, enabling the device to quickly connect to the network without manually configuring the IP address.

  5. DNS protocol: DNS (Domain Name System) converts easy-to-remember domain names into IP addresses. On the Internet, it's easier for people to remember domain names (such as www.example.com) than complex IP addresses. The DNS protocol allows domain names to be resolved into corresponding IP addresses, enabling users to access websites and resources.

  6. ICMP protocol: ICMP (Internet Control Message Protocol) is used to transmit error messages and control messages in IP networks. For example, when something goes wrong with a packet in transit, ICMP can generate an error message and notify the source host.

These protocols cooperate with each other to form the basic structure of Internet communication. The IP address acts as a bridge between these protocols, enabling data to be transmitted and exchanged in different layers of networks.

2.1.2 Port number

In computer networking, a port number is a numerical identifier used to identify a particular application or service. It is a concept used in transport layer protocols such as TCP (Transmission Control Protocol) and UDP (User Datagram Protocol). By combining IP addresses with port numbers, different applications in the network can run simultaneously on the same device, enabling multiplexing and distribution of data.

Here are some key meanings of the port numbers:

  1. Identifying Applications: Port numbers are used to identify different applications or services running on a device. Each application can listen on one or more specific port numbers in order to communicate with other devices.

  2. Multiplexing: By using port numbers, multiple applications can run simultaneously on the same device without interfering with each other. The transport layer protocol can deliver the packet to the correct application based on the destination port number.

  3. Data transmission: The port number together with the IP address constitutes a network socket (socket), allowing applications to transmit data over the network. The source port number is used by the sender and the destination port number by the receiver to determine which application the data should be delivered to.

  4. Service Identification: Some standard port numbers have been assigned to specific services or protocols. For example, HTTP typically uses port number 80, HTTPS uses port number 443, SMTP (mail transfer) uses port number 25, etc. This way, network devices and applications can recognize common services and pass data to the correct ports.

  5. Security: Port numbers are also related to network security. Firewalls and network security devices can control data traffic based on port numbers, allowing or blocking communication for specific applications or services.

  6. Dynamic allocation: In addition to some common standard port numbers, applications can also use dynamically allocated port numbers. These port numbers are temporarily assigned to applications during communication so that they can be released and reused after communication ends.

Port number is an important concept in network communication, which enables different applications to communicate over the network on the same device and ensures that data can be accurately delivered to the target application.

2.1.3 Network byte order

Network Byte Order (Network Byte Order) is discussing the byte order problem when transmitting data across different computer architectures (such as big endian and little endian) in a computer network. Different computer architectures store the endianness of multibyte data (such as integers, floating point numbers, etc.) in memory differently, which can lead to confusion and misinterpretation of data in network communications.

Network communication involves the exchange of data between multiple computers or devices. If different devices use different endianness, it may cause the following problems when sending data:

  1. Misinterpretation of data: The receiver may misinterpret the data because the bytes are in a different order than the sender. This can cause the data to be incorrectly interpreted and processed in the receiver's application.

  2. Data truncation: If data is transmitted in different endianness when sending and receiving, it may result in partial truncation or loss of data. This can compromise data integrity.

To solve these problems, network communication needs to use a consistent endianness to ensure that data can be passed and interpreted correctly between different devices. This consistent byte order is called network byte order, and is usually big-endian.

The discussion of network byte order involves how to ensure that both the sending and receiving parties can correctly interpret the data during data transmission. To achieve this, endian conversion functions such as htonl(), htons(), ntohl()and ntohs(), are used to convert between different endiannesses. This ensures that data is transmitted and interpreted consistently across the network, regardless of whether big-endian or little-endian is used.

2.2 TCP-based socket communication

2.2.1 Understanding sockets

img

Socket (Socket) is a programming interface (API) used to communicate in a computer network. It provides a mechanism to enable data transmission between different computers through the network to achieve inter-process communication.

Background and Problem: In early computer networks, a method was needed to communicate between different devices. Initial network communication is carried out through low-level network protocols, but this is too cumbersome for applications. Developers need a higher level of abstraction to handle communication details to enable data exchange between applications.

Problem solving and method: The emergence of Socket interface solves the above problems. It provides a standard API that makes it easy for applications to create, connect, send and receive data. Through Socket, the application program does not need to care about the underlying network details, but only needs to use the Socket function to realize the communication.

Role: Socket plays a key role in network communication, which enables applications to easily exchange data between different devices. Through Socket, developers can build various network applications, such as online games, chat applications, file transfer tools, network servers, etc.

Development process and changes: The development of Socket has gone through different stages. At first, it was based on traditional Unix file I/O. Later, with the development of computer networks, Socket was gradually standardized, and different Socket types (such as stream sockets, datagram sockets, etc.) and Socket functions ( Such as socket(), bind(), connect(), send(), recv(), etc.). With the advancement of network technology, Socket has been widely supported in different operating systems and programming languages.

In addition, with the rapid development of the Internet, the application range of Socket has become wider, extending from traditional network communication to Web development, real-time audio and video transmission, cloud computing and other fields. At the same time, various advanced communication protocols are also built on the basis of Socket, such as HTTP, FTP, SMTP, etc.

In short, Socket is the core concept in network programming. It plays an extremely important role in computer network communication, providing a common interface so that applications can easily communicate across networks without dealing with the underlying details. From the initial development of Unix file I/O to modern network communication, Socket has been constantly evolving to adapt to changing network requirements.

2.2.2 Communication model

img

Socket communication implementation steps analysis :

Step 1 : Create ServerSocket and Socket

Step 2 : Open the input/output stream of the Socket connected to

Step 3 : Read/write the Socket according to the protocol

Step 4 : Close the input and output streams, and Socket

Next, write a simple example. After starting the server, the client clicks the button and then connects to the server, and sends a string of strings to the server, indicating that the server is connected to the server through the Socket

2.2.3 Writing the server

Here's what the server needs to do :

Step 1 : Create a ServerSocket object and bind the listening port

Step 2 : Call the accept() method to monitor the client's request

Step 3 : After the connection is established, read the request information sent by the client through the input stream

Step 4 : Send response information to the client through the output stream

Step 5 : Close related resources

Code:

#include <iostream>
#include <cstring>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

int main() {
    int serverSocket, clientSocket;
    struct sockaddr_in serverAddr;
    struct sockaddr_in clientAddr;
    socklen_t clientAddrLen = sizeof(clientAddr);
    
    // 1. 创建服务器端 Socket
    serverSocket = socket(AF_INET, SOCK_STREAM, 0);
    
    // 配置服务器地址
    memset(&serverAddr, 0, sizeof(serverAddr));
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_addr.s_addr = INADDR_ANY; // 任意地址
    serverAddr.sin_port = htons(12345); // 端口号转换为网络字节序
    
    // 2. 绑定端口和地址
    bind(serverSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr));
    
    // 3. 监听连接请求
    listen(serverSocket, 5); // 允许最大排队连接数为5
    
    std::cout << "~~~ 服务端已就绪,等待客户端接入 ~~~" << std::endl;
    
    // 4. 等待客户端连接
    clientSocket = accept(serverSocket, (struct sockaddr*)&clientAddr, &clientAddrLen);
    
    char clientIp[INET_ADDRSTRLEN];
    inet_ntop(AF_INET, &(clientAddr.sin_addr), clientIp, INET_ADDRSTRLEN);
    std::cout << "客户端接入,客户端 IP 地址:" << clientIp << std::endl;
    
    // 5. 读取客户端信息
    char buffer[1024];
    memset(buffer, 0, sizeof(buffer));
    
    while (recv(clientSocket, buffer, sizeof(buffer), 0) > 0) {
        std::cout << "客户端发送过来的信息:" << buffer << std::endl;
        memset(buffer, 0, sizeof(buffer));
    }
    
    // 6. 关闭连接
    close(clientSocket);
    close(serverSocket);
    
    return 0;
}

2.2.4 Client writing

What the client has to do is :

Step 1 : Create a Socket object, indicating the address and port number of the server to be linked

Step 2 : After the link is established, send request information to the server through the output stream

Step 3 : Get the server response information through the output stream

Step 4 : Close related resources

Code:

#include <iostream>
#include <cstring>
#include <cstdlib>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

int main() {
    // 创建客户端 Socket
    int clientSocket = socket(AF_INET, SOCK_STREAM, 0);
    if (clientSocket == -1) {
        std::cerr << "Error creating socket!" << std::endl;
        return 1;
    }
    
    // 配置服务器地址和端口
    struct sockaddr_in serverAddr;
    memset(&serverAddr, 0, sizeof(serverAddr));
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(12345); // 端口号转换为网络字节序
    if (inet_pton(AF_INET, "172.16.2.54", &serverAddr.sin_addr) <= 0) {
        std::cerr << "Invalid address or address family!" << std::endl;
        return 1;
    }
    
    // 连接到服务器
    if (connect(clientSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) == -1) {
        std::cerr << "Error connecting to server!" << std::endl;
        close(clientSocket);
        return 1;
    }
    
    // 获取客户端 IP 地址
    char clientIp[INET_ADDRSTRLEN];
    if (inet_ntop(AF_INET, &serverAddr.sin_addr, clientIp, INET_ADDRSTRLEN) == nullptr) {
        std::cerr << "Error converting IP address!" << std::endl;
        close(clientSocket);
        return 1;
    }
    
    // 发送消息到服务器
    const char* message = "客户端:";
    send(clientSocket, message, strlen(message), 0);
    send(clientSocket, clientIp, strlen(clientIp), 0);
    send(clientSocket, " 接入服务器!", strlen(" 接入服务器!"), 0);
    
    // 关闭连接
    close(clientSocket);
    
    return 0;
}

2.3 Based on UDP

2.3.1 Server implementation

Server implementation steps:

Step 1 : Create a DatagramSocket, specify the port number
Step 2 : Create a DatagramPacket
Step 3 : Receive the data information sent by the client
Step 4 : Read the data

#include <iostream>
#include <cstring>
#include <cstdlib>
#include <arpa/inet.h>
#include <unistd.h>

int main() {
    /*
     * 接收客户端发送的数据
     */
    // 1. 创建服务器端套接字
    int serverSocket = socket(AF_INET, SOCK_DGRAM, 0);
    if (serverSocket == -1) {
        std::cerr << "Error creating socket!" << std::endl;
        return 1;
    }

    // 2. 配置服务器地址
    struct sockaddr_in serverAddr;
    memset(&serverAddr, 0, sizeof(serverAddr));
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_addr.s_addr = INADDR_ANY; // 使用本地所有可用地址
    serverAddr.sin_port = htons(12345); // 端口号转换为网络字节序

    // 3. 绑定端口和地址
    if (bind(serverSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) == -1) {
        std::cerr << "Error binding socket!" << std::endl;
        close(serverSocket);
        return 1;
    }

    // 4. 接收客户端发送的数据
    struct sockaddr_in clientAddr;
    socklen_t clientAddrLen = sizeof(clientAddr);
    char data[1024];
    memset(data, 0, sizeof(data));

    std::cout << "**** 服务器端已经启动,等待客户端发送数据 ****" << std::endl;
    ssize_t bytesRead = recvfrom(serverSocket, data, sizeof(data), 0, (struct sockaddr*)&clientAddr, &clientAddrLen);
    if (bytesRead == -1) {
        std::cerr << "Error receiving data!" << std::endl;
        close(serverSocket);
        return 1;
    }
    data[bytesRead] = '\0'; // 添加字符串结尾标志
    std::cout << "我是服务器,客户端说:" << data << std::endl;

    /*
     * 向客户端响应数据
     */
    // 1. 获取客户端的地址和端口
    struct sockaddr_in responseAddr = clientAddr;
    socklen_t responseAddrLen = sizeof(responseAddr);

    // 2. 定义响应的数据
    const char* responseMsg = "欢迎您!";

    // 3. 响应客户端
    ssize_t bytesSent = sendto(serverSocket, responseMsg, strlen(responseMsg), 0, (struct sockaddr*)&responseAddr, responseAddrLen);
    if (bytesSent == -1) {
        std::cerr << "Error sending response!" << std::endl;
    }

    // 4. 关闭套接字
    close(serverSocket);

    return 0;
}

2.3.2 Client implementation

Client implementation steps:

Step 1 : Define sending information
Step 2 : Create DatagramPacket, which contains the information to be sent
Step 3 : Create DatagramSocket
Step 4 : Send data

#include <iostream>
#include <cstring>
#include <cstdlib>
#include <arpa/inet.h>
#include <unistd.h>

int main() {
    /*
     * 向服务器端发送数据
     */
    // 1. 定义服务器地址和端口号
    struct sockaddr_in serverAddr;
    memset(&serverAddr, 0, sizeof(serverAddr));
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(8800); // 端口号转换为网络字节序
    if (inet_pton(AF_INET, "127.0.0.1", &serverAddr.sin_addr) <= 0) {
        std::cerr << "Invalid address or address family!" << std::endl;
        return 1;
    }

    // 2. 定义要发送的数据
    const char* data = "用户名:admin;密码:123";

    // 3. 创建 UDP 套接字
    int clientSocket = socket(AF_INET, SOCK_DGRAM, 0);
    if (clientSocket == -1) {
        std::cerr << "Error creating socket!" << std::endl;
        return 1;
    }

    // 4. 发送数据报到服务器
    ssize_t bytesSent = sendto(clientSocket, data, strlen(data), 0, (struct sockaddr*)&serverAddr, sizeof(serverAddr));
    if (bytesSent == -1) {
        std::cerr << "Error sending data!" << std::endl;
        close(clientSocket);
        return 1;
    }

    /*
     * 接收服务器端响应的数据
     */
    // 1. 创建用于接收数据的缓冲区
    char reply[1024];
    memset(reply, 0, sizeof(reply));

    // 2. 接收服务器响应的数据
    struct sockaddr_in responseAddr;
    socklen_t responseAddrLen = sizeof(responseAddr);
    ssize_t bytesRead = recvfrom(clientSocket, reply, sizeof(reply), 0, (struct sockaddr*)&responseAddr, &responseAddrLen);
    if (bytesRead == -1) {
        std::cerr << "Error receiving data!" << std::endl;
    } else {
        std::cout << "我是客户端,服务器说:" << reply << std::endl;
    }

    // 3. 关闭套接字
    close(clientSocket);

    return 0;
}

Guess you like

Origin blog.csdn.net/qq_64893500/article/details/132228200