Alamofire learning (I) Network foundation

Alamofire (2) URLSession

Alamofire (3) Background download principle

@TOC

Network Basics

1. Network architecture

1.1 Network OSI Layer 7 protocol

The following is a model diagram of the protocol layer from bottom to top:

  • OSI layer 7 protocol
Layer of the OSI function TCP/IP protocol family
The application layer File transfer, E-mail, file services, virtual terminals TFTP, HTTP, SNMP, FTP, SMTP, DNS, Telnet
The presentation layer Data formatting, code conversion, data encryption No agreement
The session layer To release or establish a connection with another contact No agreement
The transport layer Provide an end-to-end interface TCP, UDP
The network layer Select a route for the packet IP, ICMP, RIP, OSPF, BGP, IGMP
Data link layer Transmission of addressed frames and error detection SLIP, CSLIP, PPP, ARP, RARP, MTU
The physical layer The transmission of data over physical media as binary data ISO2110, IEEE802, IEEE802.2
  • TCP/IP five-layer protocol
TCP/IP layer Network equipment
The application layer
The transport layer Layer 4 switches and routers work at Layer 4
The network layer Router and Layer 3 switch
Data link layer Network bridge (now rarely used), Ethernet switch (Layer 2 switch), network adapter (actually network adapter is half of the physical layer, half of the data link layer)
The physical layer Repeaters, hubs, and what is commonly known as twisted-pair cables also work in the physical layer

1.1.1. Introduction to the OSI Layer 7 protocol

OSI stands for Open System Interconnect.

The classification of the layers of the OSI seven-layer reference model follows the following principles:

1. All network nodes in the same layer have the same hierarchical structure and have the same functions. 2. Communicate between adjacent layers of the same node through interfaces (which can be logical interfaces). Each layer in the seven-tier structure uses the services provided by the next layer and provides services to its upper layer. 4. The same layer of different nodes implements communication between peer layers according to the protocol.

  • Layer 1: PhysicalLayer

Specifies the mechanical, electrical, functional, and process characteristics of communications equipment used to establish, maintain, and dismantle physical link connections. Specifically, the mechanical characteristics of the network connection required the size of the connector, the number and arrangement of pins, etc. The electrical characteristics specify the signal level size, impedance matching, transmission rate distance limit and so on when transmitting bit stream on physical connection. Functions and features define the functions of each line between DTE and DCE by assigning precise signal meanings to each signal. Protocol characteristics define a set of operation procedures for bit stream transmission using signal lines. It refers to the operation series of DTE and DCE on each circuit for establishing, maintaining, and exchanging information of physical connections. At this level, the units of data are called bits. Typical specification representatives belonging to the physical layer definition include EIA/TIA RS-232, EIA/TIA RS-449, V.35, RJ-45, etc.

  • Layer 2: DataLinkLayer

Based on the bitstream service provided by the physical layer, the data link between adjacent nodes is established, and the error-free transmission of data frames on the channel is provided through error control, and the action series of each circuit is carried out. The data link layer provides reliable transport over unreliable physical media. The functions of this layer include: physical address addressing, data framing, flow control, data error detection, retransmission, etc. At this level, the units of data are called frames. Data link layer protocols include SDLC, HDLC, PPP, STP, frame relay, etc.

Data link layer protocol:

  • Layer 3: Network Layer

Two computers communicating in a computer network may pass through many data links and may also pass through many communication subnets. The task of the network layer is to select the appropriate internetwork routing and switching nodes to ensure the timely transmission of data. The network layer consists of packets of frames provided by the data link layer. The packets contain the network layer packet header, which contains the logical address information – the network address of the source site and destination site address. If you are talking about an IP address, then you are dealing with layer 3 issues, which are “packets”, not layer 2 “frames”. IP is part of the layer 3 problem, along with several routing protocols and the Ground address resolution protocol (ARP). Everything about routing is handled at this layer 3. Address resolution and routing are important purposes for Layer 3. Network layer can also realize congestion control, Internet interconnection and other functions. At this level, the units of data are called packets. Network layer protocols include IP, IPX, RIP, and OSPF.

Network layer protocol:

Network layer protocol function
IP(Internet Protocol) IP is the most important protocol at the network layer. Its functions are as follows: providing logical addressing, routing, and packet encapsulation and unencapsulation. ICMP, ARP, and RARP support IP work.
ICMP(Internet Control Message Protocol) ICMP is a management protocol that provides information services for IP addresses. ICMP messages are carried in IP packets.
ARP(Address Resolution Protocol) Dynamic mapping of IP addresses to hardware addresses is implemented, that is, hardware addresses are obtained based on known IP addresses.
RARP(Reverse Address Resolution Protocol) Realize dynamic mapping of hardware addresses to IP addresses, that is, obtain corresponding IP addresses based on known hardware addresses.
  • Layer 4: Transport Layer

The layer 4 data unit is also called packets. But there are segments when you talk about specific protocols like TCP. TCP data segments and UDP data segments are datagrams. This layer is responsible for capturing all the information, so it must keep track of fragments of data units, packets arriving out of order, and other hazards that may occur in transit. Layer 4 provides transparent, reliable end-to-end (end user to end user) data transfer services for the upper layer. Transparent transmission means that the transmission layer hides the details of the communication transmission system from the upper layer during communication. Transport layer protocols include TCP, UDP, and SPX. The transmission layer is the most important and critical layer in OSI. It is the only layer responsible for the overall data transmission and control.

The transport layer provides an end-to-end data exchange mechanism to check the number and order of packets. The transport layer provides reliable transmission service to its upper three layers, such as the session layer, and provides reliable destination site information to the network layer

At this level, the units of data are called segments

Main functions:

① : Provide transport service for end-to-end connection

② : This kind of transport service is divided into reliable and unreliable, among which Tcp is the typical reliable transport, while Udp is the unreliable transport

③ : Provide end-to-end connection flow control, error control, Quality of Service (QoS) and other management services

The agreements included are as follows:

TCP: a transmission control protocol with low transmission efficiency and high reliability

UDP: user datagram protocol, suitable for transmission of data with low reliability requirements and a small amount of data (such as QQ)

DCCP, SCTP, RTP, RSVP, and PPTP

For more details please refer to

Transport layer protocol:

  • Layer 5: Session Layer

This layer can also be called the meeting layer or the conversation layer. At the session layer and above, the units of data transmission are no longer individually named, but collectively referred to as messages. The session layer does not participate in the specific transport and provides mechanisms for establishing and maintaining communication between applications, including access validation and session management. For example, the server authenticates the user login by the session layer.

  • Presentation Layer

This layer addresses the syntactic representation of the advocacy message. It converts the data to be exchanged from an abstract syntax suitable for a user to a transport syntax suitable for use within the OSI system. That is, to provide formatted presentation and transformation data services. The presentation layer is responsible for data compression and decompression, encryption and decryption.

  • Layer 7: Application Layer

The application layer provides the interface for the operating system or network applications to access network services. Application layer protocols include Telnet, FTP, HTTP, and SNMP.

Main functions:

  1. Provide interfaces for users and handle specific applications;
  2. Data encryption, decryption, compression, decompression;
  3. Define standards for data presentation.

Application layer protocol:

Protocols and functions of the application layer:

Application layer protocol function
Hypertext Transfer Protocol HTTP This is a basic client/server access protocol; The browser sends a request to the server, and the server responds to the corresponding web page
File transfer protocol FTP Provides interactive access, client-server mode, connection-oriented reliable transport service using TCP Main functions: Reduce/eliminate file incompatibility between different operating systems
TELNET is the remote login protocol Client server mode, can adapt to many computer and operating system differences, network virtual terminal NVT significance
Simple Mail Transfer protocol SMTP Client/Server mode, connection-oriented basic functions: letter writing, transmission, transmission report, display letters, receiver processing letters
DNS Domain name resolution protocol DNS is an Internet service that converts domain names into IP addresses
Simple file transfer protocol TFTP Client server mode, using UDP datagrams, only supports file transfer, does not support interaction, TFTP code occupies a small memory
Simple Network Management Protocol (SNMP) The SNMP model has four components: managed node, management station, management information, and management protocol SNMP agent: managed node running the SNMP management process. Object: variables describing devices. Management information base (MIB) : data structure storing all objects
DHCP Dynamic host configuration protocol Boot file name, empty terminator, genus name, or empty in discovery protocol, restricted directory pathname in DHCP provisioning protocol Options – Optional parameter field, refer to the selection file in the Define Selection list

1.1.2. The role of OSI seven layers

The following diagram illustrates the effect of each of these simple layers:

2 the TCP/IP protocol

Transmission Control Protocol (TCP) and User Datagram Protocol (UDP) belong to transport layer protocols. TCP provides reliable data transmission under IP environment, and it provides services including data transmission, reliability, effective flow control, full duplex operation and multiplexing. Through connection-oriented, end-to-end, and reliable packet delivery. Generally speaking, it is to open up a connected channel for the data sent in advance, and then send data; UDP does not provide reliability, flow control, or error recovery for IP. Generally speaking, TCP corresponds to applications with high reliability requirements, while UDP corresponds to applications with low reliability requirements and low transmission economy. TCP supports application protocols such as Telnet, FTP, and SMTP. UDP supports the following application-layer protocols: NETWORK File System (NFS), Simple Network Management Protocol (SNMP), DOMAIN Name System (DNS), and File Transfer Protocol (TFTP). TCP/IP is independent of the data link layer and physical layer, which is an important feature of TCP/IP

2.1. TCP/IP data encapsulation

Each layer of TCP/IP allows data to travel over the network. These layers exchange information with each other using pdUs (protocol data units) to ensure that network devices can communicate with each other

The process of the protocol stack passing down data and adding headers and tailing is called encapsulation. After the data is encapsulated and transmitted over the network, the receiving device will delete the added information and decide how to transfer the data along the protocol stack to the appropriate application program according to the information in the header. This process is called decapsulation. Peer layers of different devices communicate with each other by encapsulation and unencapsulation.

2.2. TCP/IP data encapsulation process

  1. Here’s a first look:

    Used by the transport layerTCPorUPDFor example, IP is used at the network layer and Ethernet is used at the link layer. The packet encapsulation process in TCP/IP is shown in the figure above. User data through the application layer protocol encapsulation after transmission layer, transmission layer encapsulation TCP head, to the network layer, network layer encapsulation IP head, and then to the data link layer, data link layer encapsulation Ethernet frame head and frame tail, to the physical layer, the physical layer in the form of bit stream data sent to the physical line.

  2. TCP packet format

  3. TCP header format

  • TCP uses IP as the network layer protocol. TCP data segments are encapsulated in an IP packet. The TCP Data segment consists of the TCP Head and TCP Data.

    TCP has a header of up to 60 bytes. If there are no optional fields, the normal length is 20 bytes. The TCP Head consists of the fields identified in the figure above. Several commonly used fields are listed here.

field function note
16-bit source port number TCP assigns a source port number to the source application
16-bit destination port number Port number of the destination application. Each TCP segment contains the source and destination port numbers, which are used to find the originating and ending application processes. These two values together with the source IP address and destination IP address in the IP header uniquely determine a TCP connection. note
32-bit serial number Identifies the byte stream of data sent from the TCP source to the TCP receiver.
32-bit confirmation serial number The acknowledgment sequence number contains the next sequence number that the end that sent the acknowledgment expects to receive. Confirm that the serial number is the last data successfully received plus 1.
4 bit head length Indicates the number of 32-bit characters in the header. The maximum length of the TCP header is 60 bytes note
16 bit window size Represents the bytes that the receiver expects to receive. Since this field is 16 bits, the maximum window size is 65535 bytes.
16-bit check sum Check and cover the entire TCP packet segment, including the TCP header and TCP data. This value is calculated and stored by the originator and verified by the receiver
  • Six flag bits
field function note
UNG logo Indicates whether the emergency pointer is valid
ACK flag Indicates whether the confirmation number is valid. We regard the TCP packet segment with ACK flag as the acknowledgement packet segment
PSH logo The receiver application is prompted to immediately read the data from the TCP receive buffer to make room for subsequent data to be received
RST sign Indicates that the peer party is required to re-establish the connection. The TCP packet segment carrying the RST flag is the reset packet segment
The SYN flag Indicates a request to establish a connection. We regard the TCP packet segment carrying the SYN flag as the synchronization packet segment
FIN logo Indicates that the local end is about to close the connection. The TCP packet segment carrying the FIN flag is the end packet segment

2.3. TCP three-way handshake (establishes connection) and four-way wave (disconnects connection)

2.3.1 TCP three-way handshake

2.3.1.1 Introduction to the TCP three-way handshake

  1. As shown in the figure above, we can clearly see the process of three handshakes. The specific process is as follows:
  • First time: client — > server This time the server knows that the client is about to establish a connection
  • The second time: client < — server The client knows that the server received the connection request
  • Third time: client — > server At this point, the server knows that the client has received its response, and it can assume that the client has established a connection with the server.

To get a clearer picture of the process, take a look at this motion picture again:

The SYN, ACK, PSH, FIN, RST, URG in the figure are the 6 flag bits in the TCP packet header format explained above.

field function note
UNG logo Indicates whether the emergency pointer is valid
ACK flag Indicates whether the confirmation number is valid. We regard the TCP packet segment with ACK flag as the acknowledgement packet segment
PSH logo The receiver application is prompted to immediately read the data from the TCP receive buffer to make room for subsequent data to be received
RST sign Indicates that the peer party is required to re-establish the connection. The TCP packet segment carrying the RST flag is the reset packet segment
The SYN flag Indicates a request to establish a connection. We regard the TCP packet segment carrying the SYN flag as the synchronization packet segment
FIN logo Indicates that the local end is about to close the connection. The TCP packet segment carrying the FIN flag is the end packet segment
Sequence number Seq number, which is a 32-bit number, identifies the byte stream to be sent from the TCP source to the TCP destination. This number is marked when the initiator sends data
Acknowledge number Ack id, which contains 32 bits. The Ack id field is valid only when the Ack flag bit is 1. Ack=Seq+1
2.3.1.2 TCP three-way handshake Analysis

In the picture above, we can see the process of three handshakes roughly:

  1. In the beginning, both the client and the server are inCLOSEAt this point, the client sends a connection request to the server and the server passively accepts the connection request.
  2. TCPThe server process first creates the transfer control block TCB, ready to accept the client process connection request, at this time the server will enterLISTEN(Listening) status.
  3. TCPThe client process also creates TCB, and then sends a connection request message to the server. At this time, the synchronization flag bit in the packet header is displayedSYN=1, and select an initial serial numberseq = x, the TCP client process entersSYN-SENT(Synchronization sent status) Status. TCP,SYNMessage segment (SYN=1Cannot carry data, but needs to consume a sequence number.
  4. TCPAfter receiving the request packet, the server sends an acknowledgement packet if it agrees to connect. In acknowledgement messageACK=1, SYN=1, confirm that the serial number isx+1, also initialize a serial number for yourselfseq = yAt this point, the TCP server process entersSYN-RCVD(Synchronous received) status. This message also does not carry data, but again consumes a serial number.
  5. TCPWhen the client process receives an acknowledgement, it sends an acknowledgement to the server. Acknowledgement of messageACK=1, confirm that the serial number isy+1And its serial number isx+1.
  6. At this point,TCPThe connection is established and the client entersESTABLISHEDStatus of an established connection. When the server receives the client’s acknowledgement, it also entersESTABLISHEDState, after which the two parties can start communicating.

A lot of people here are wondering, why three times, not two times or four times?

  • Why not do it twice?

A: It is used to prevent invalid connection request packets from being sent to the server and causing errors. If you are using two handshake connection is established, suppose there is such a scenario, the client sends the first request connection and not lost, just because the retention time is too long in the network, as a result of the TCP client has not received the confirmation message, thought the server did not receive, at this time to send this message to the server, The client and server then complete the connection with two handshakes, transfer data, and close the connection. Because the network is unblocked and reaches the server, the message should be invalid. However, the two-handshake mechanism will allow the client and server to establish a connection again, which will lead to unnecessary errors and resource costs. If the three-way handshake is used, even if the invalid packet is sent, the server receives the invalid packet and replies with an acknowledgement message, but the client does not send an acknowledgement again. Since the server does not receive an acknowledgement, it knows that the client has not requested a connection.

  • Why not four times?

A: This is easy to explain, because three times is enough, four times is more than enough. It’s a waste of resources.

2.3.2 TCP wave four times

Here’s a sequence of four waves:

  • Let’s take a look at the four handshakes above:
  1. After data transfer is complete, both parties can release the connection. Both the client and the server are inESTABLISHEDState, then the client actively disconnects and the server passively disconnects.
  2. The client process sends a connection release packet and stops sending data. Release the data header,FIN=1And its serial number isseq=u(equal to the ordinal number of the last byte of the previously transmitted data plus 1), the client entersFIN-WAIT-1(Terminate wait 1) status. TCP,FINA message segment consumes an ordinal number even if it carries no data.
  3. The server receives a connection release packet and sends an acknowledgement packet.ACK=1, confirm that the serial number isu+1And bring your own serial numberseq=vAt this point, the server entersCLOSE-WAIT(Off wait) state.TCPThe server notifies the higher-level application process that the client is released to the server in a semi-closed state, meaning that the client has no data to send, but the client still receives data if the server sends it. It’s going to last for a while, which is the wholeCLOSE-WAITDuration of the state.
  4. After receiving an acknowledgement request from the server, the client entersFIN-WAIT-2(Terminate wait 2) state, waiting for the server to send a connection-release message (the final data sent by the server is also needed before this)
  5. After sending the final data, the server sends a connection-release message to the client,FIN=1, confirm that the serial number isv+1Since the server is in the semi-closed state, it is likely that the server sent some more data, assuming that the serial number isseq=wAt this point, the server entersLAST-ACK(Final confirmation) status, waiting for the client’s confirmation.
  6. After receiving the connection release packet from the server, the client must send an acknowledgement message.ACK=1, confirm that the serial number isw+1And his serial number isu+1At this point, the client entersTIME-WAIT(Time wait) status. Notice The TCP connection is not released and must be passed2 ∗ MSL(Maximum Packet segment life) when the client revokes the correspondingTCBAfter enteringCLOSEDState.
  7. Once the server receives an acknowledgement from the client, it immediately enters the serverCLOSEDState. Also, undoTCBAfter the end of this timeTCPThe connection. As you can see,Server EndTCPThe connection time is earlier than the client.
  • Take a look at a dynamic diagram to understand:

    (1) a man and a woman are dating in a cafe. The man (client) first asks:What do you think of me?(first handshake) (2).I think you're handsomeThen he asked the man:Do you think I'm pretty?“To confirm the man’s opinion. Hearing the woman’s answer, the man was so happy that he could not wait to take her hand and say:I think you're my goddess. Let's be together, to this hand success. (Third handshake) Establish a connection. (4). If you can’t hold hands if any of the above three steps are missing, you need both people to agree and confirm before you can establish a connection.

And four times to wave process, is similar to such a scenario: (1). Dating men and women get along together for a while, began to make antinomy, female temperament more urgent, first to break up (the woman is equal to the client) woman said: I’ve had enough of you, you are a dwarf is poor, I want prince charming Grosvenor LTD command ability should be right. (First wave: FIN M) After the first wave, it enters the Finish_Wait_1 state (2). The man thinks the woman is very good, very beautiful, but a little stubborn, do not want to break up, the man still want to say a lot of words to the woman to retain. At this time the man said: I received you want to break up the message (ACK +1), and then to the woman said a lot of retention words, only at this time the man to the woman spoke (server — “client) half duplex. (Second wave: ACK M+1) (After receiving the first wave message, the server enters the Close_Wait state, but can also send the uncompleted message to the client, and then send an acknowledgement packet: ACK = M+1) The man thought very close said a lot of words to retain are invalid, and then the male despair said a: really want to break up again confirm (FIN N) and then wait for the woman’s answer, no longer to the woman. (third wave) (now the server enters the LAST_ACK state)

(4). The woman hear the man said, after some hesitation, if she wants to go back, can tell a man: I don’t want to break up So break up will fail, if she persisted in her native instead, determined to break up, she would say: I want to for a long time, we really don’t appropriate, we still break up (the fourth wave: ACK=1, ACK= K +1). (At this point, the client enters the Time_Wait state and waits for 2MSL to close the connection.) If the man decides to break up with the woman, he will directly Close() the call status and do not need to send messages to the woman. If the man decides not to break up with the woman, he will tell the woman again: We do not break up, and the breakup has failed. (In this case, the server will close the connection state before the client, and the client will have to wait a maximum of 2MSL)

  • Why does the client end up waiting for 2*MSL?

MSL (Maximum Segment Lifetime) : TCP allows different implementations to set different MSL values.

First, ensure that the client sends the final ACK packet to reach the server, because the ACK packet may be lost, standing in the server’s perspective, I have already sent the FIN + ACK message request disconnect, the client also did not give me response, should be I send the request of the disconnect message it did not receive, then the server will send a again, The client receives the retransmitted message within the 2MSL period, responds with a message, and restarts the 2MSL timer.

Second, prevent “invalid connection request message segment” as mentioned in “three-way handshake” from appearing in this connection. After the client sends the last acknowledgement message, in this 2MSL time, all the message segments generated during the duration of the connection can be removed from the network. In this way, the new connection does not contain the request packets of the old connection.

  • Why three handshakes? Is two okay?

Answer: First of all, two times is obviously no. A counter example may be given to illustrate the situation. Xie Xiren version of “computer network” example is that the connection request message of “failed” in such a case: the first connection request from the client message segment is not lost, but in a network junction point of the stranded for a long time, so that has been delayed to release after a certain time to reach the server connection. Originally, this is an invalid packet segment. However, after the server receives the invalid connection request packet segment, it mistakenly thinks it is a new connection request sent by the client. Then the client sends a confirmation message to agree to establish a connection. Assuming that the “three-way handshake” is not adopted, a new connection is established as soon as the server sends an acknowledgement. Since the client does not send a connection request, it ignores the server’s confirmation and does not send data to the server. However, the server assumes that the new transport connection has been established and waits for data from the client. As a result, many of the server’s resources are wasted. The three-way handshake prevents this from happening. For example, the client does not issue an acknowledgement to the server’s acknowledgement. When the server receives no acknowledgement, it knows that the client is not trying to establish a connection.” . The main purpose is to prevent the server from wasting resources by waiting. By extension, the wave is usually four times. Why? Can three waves be done in some cases? In some cases, the third wave can be completed. If the local end closes the connection and receives a FIN packet from the peer end, the local end can send the FIN packet and the ACK packet to the peer end together. It becomes three times.

  • Why is establishing a connection a three-way handshake, but closing a connection a four-way wave?

1. When establishing a connection, the server receives a SYN packet in LISTEN state and sends the ACK and SYN packets to the client.

2. Close connection, the server receives the other side of the FIN message, just said to each other can no longer send data but also receives the data, and the oneself also is not necessarily all data are sent to each other, so their can immediately shut down, also can send some data to each other, then send the FIN message now agreed to close the connection to the other side, therefore, The ACK and FIN are usually sent separately, resulting in an extra ACK.

  • Why does the TIME_WAIT state take 2MSL to return to CLOSE?

A: Although it is reasonable that all four packets are sent and we can directly enter the CLOSE state, we must pretend that the network is unreliable and the last ACK can be lost. Therefore, the TIME_WAIT state is used to resend ACK packets that may be lost. The Client sends the last ACK reply, but the ACK may be lost. If the Server does not receive an ACK, it repeatedly sends FIN fragments. Therefore, the Client cannot shut down immediately. It must confirm that the Server received the ACK. The Client enters the TIME_WAIT state after sending an ACK. The Client sets a timer and waits for 2MSL of time. If a FIN is received again within that time, the Client resends the ACK and waits for another 2MSL. The so-called 2MSL is twice the MSL(Maximum Segment Lifetime). MSL refers to the maximum lifetime of a fragment in the network. 2MSL refers to the maximum time required for a send and a reply. If the Client does not receive a FIN again until 2MSL, the Client concludes that the ACK has been successfully received and terminates the TCP connection.

  • What does the three-way handshake do?

2) Inform the peer end of the packet ID selected by the local end for communication. 3) Prevent the invalid connection request packet segment from being suddenly transmitted to the server, resulting in errors

  • What stage of the three-way handshake is prone to attack?

A: Syn flood attack, or SYN overflow attack, is typical. Syn overflow attacks occur in the second stage. If a client forges a large number of the first SYS synchronization messages, the server in turn spends a lot of resources saving the client’s information and verifying it. The actual verification fails, but it takes some time. This is because the server will perform a second handshake to confirm the failure. If a large number of SYN synchronization packets flood to the server in a short time, the server resources may be exhausted. As a result, normal clients may fail to receive any response.

  • What phase of the three-way handshake is unusual?

Answer: The second phase may be abnormal, if the corresponding port of the server is not opened, the RST reset message will be returned, and the grip fails. In addition, listen creates an upper limit of listening queues and may fail.

  • What is the difference between TIME_WAIT and CLOSE_WAIT?

Answer: CLOSE_WAIT is the state in which the passively closed end receives the close request (FIN packet segment) from the peer end and sends an ACK. This state indicates that the peer end has received the close request, but the local end has not completed the work and is not closed. TIME_WAIT status Indicates the status of the end that actively closes the local end after receiving the close request (FIN packet segment) from the peer end and sending the ACK. The status is as follows: Both parties have done their work just to ensure that late datagrams can be discarded and reliably terminate the TCP connection.

  • Why does TIME_WAIT exist?

Answer: The TIME_WAIT state is a state after the end that disconnects actively receives a FIN packet from the peer and sends an ACK packet. Meaning: 1) Ensure that late packet segments can be identified and discarded. 2) Ensure reliable termination of TCP connections. Ensure that the peer end receives the last ACK. If the ACK is lost, the local end can accept the FIN packet retransmitted from the peer end and resend the ACK in TIME_WAIT state. So TIME_WAIT exists for 2MSL.

  • What if the connection has been established, but the client suddenly fails?

TCP has a keepalive timer, so obviously, if the client fails, the server can’t wait forever and waste resources. The server resets this timer every time it receives a request from the client, usually for two hours. If it does not receive any data from the client within two hours, the server sends a probe segment, which is then sent every 75 minutes. If there is no response after 10 probe packets are sent, the server assumes that the client is faulty and closes the connection.

2.4. TCP Acknowledgement and reply mechanism (ACK mechanism)

  • TCP numbers each byte of data, which is the sequence number.

  • Each ACK comes with an acknowledgement sequence number that tells the sender what data I’ve received; Where are you going to start next time? For example, if the client sends 1005 bytes of data to the server and the server returns 1003, the server only receives data from 1 to 1002. 1003, 1004, and 1005 are not received. At this point, the client will resend from 1003.

2.5. TCP timeout retransmission mechanism

  • After host A sends data to HOST B, the data cannot reach host B due to network congestion. If host A does not receive an acknowledgement from host B within A specified period of time, host A resends the data. However, host A does not receive an acknowledgement from host B, or the ACK may be lost.

  • In this case, host B receives a lot of duplicate data. TCP then needs to identify which packets are duplicate and discard the duplicate packets. At this time, using the serial number mentioned above, it is easy to do the weight.

  • How is the timeout period determined? Ideally, find a minimum time within which the “confirmation reply is guaranteed to return.” However, the length of this time varies with the network environment. If the timeout period is set too long, the overall retransmission efficiency will be affected. If the timeout is set too short, repeated packets may be sent frequently. TCP dynamically calculates the maximum timeout to ensure high performance communication in any environment.

In Linux (and BSD Unix and Windows as well), the timeout is controlled in units of 500ms, and the timeout for each determined timeout retransmission is an integer multiple of 500ms. If there is still no reply after a retransmission, wait for the retransmission after 2500ms. If there is still no reply, wait 4500ms for retransmission. And so on, exponentially increasing. When the number of retransmission times reaches a certain value, TCP considers that the network is abnormal or the peer host is abnormal and forcibly closes the connection.

2.6. TCP sliding window mechanism

  1. Take a look at the following image:

    TCP sliding window technology adjusts the data transfer between two hosts by dynamically changing the window size. Each TCP/IP host supports full-duplex data transmission, so TCP has two sliding Windows: one for receiving data and one for sending data. TCP uses the affirmative confirmation technique, where the confirmation number refers to the next expected byte.

  2. As shown in the figure, data is sent in one direction as an example to explain how the sliding window realizes flow control. The server sends four data segments with a size of 1024 bytes to the client, in which the window size of the sender is 4096. The client responds with ACK4097, and the window size is adjusted to 2048, indicating that the client (i.e. the receiver) buffer can only process 2048 bytes of data segments. The sender then changes its transmission rate. Send A data segment size of 2048 that can be received by the receiver.
  • The sliding window

The window size is the maximum value at which data can continue to be sent without waiting for a confirmation reply. The size of the window above is 4000 bytes (four segments). When the first four segments are sent, there is no need to wait for any ACK. After receiving the first ACK, the window moves back and continues to send segments 5, 6, 7, 8… Because this window keeps sliding backwards, it is called a sliding window. In order to maintain this sliding window, the operating system kernel needs to create a send buffer to keep track of what data is currently unresponded. Only data that has been acknowledged by the ACK can be deleted from the buffer.

  • If a packet is lost, how can it be retransmitted? At this time, two cases are discussed:

    • 1. The packet has been received, but the acknowledgement ACK is lost. In this case, partial ACK loss is not a big deal because subsequent acks can be used to confirm which packets have been received.

    • 2. Packet loss. As shown below: After a packet is lost, the sender receives ACK messages like 1001, which reminds the sender that “I want 1001”. If the sender receives the same ACK message with 1001 for three consecutive times, It will resend the corresponding data 1001-2000 and when the receiver receives 1001, it will return an ACK of 7001 because 2001-7000 was already received by the receiver and put into the receive buffer in the kernel of the receiver’s operating system.

2.7. TCP flow control

2.7.1 What is Flow Control

The speed at which a receiver can process data is limited. If the sender sends the packet too fast, the buffer of the receiver will be filled up. If the sender continues to send the packet, packet loss will occur, and a series of chain reactions such as packet loss and retransmission will occur. Therefore, TCP determines the sending speed of the receiving end according to the processing capability of the receiving end. This mechanism is called Flow Control.

2.7.2 Flow control process

  1. As shown above, process overview:
  • The receiver puts the size of the buffer it can receive into the “window size” field in the TCP header.
  • Notify the sender by ACK;
  • The larger the window size is, the higher the network throughput is.
  • Once the receiver finds that its buffer is nearly full, it notifies the sender by setting the window size to a smaller value.
  • After receiving notifications of this size, the sender will slow down its own sending speed.
  • If the receiver buffer is full, the window is set to 0;
  • At this time, the sender no longer sends data, but needs to periodically send a window detection data segment, so that the receiver tells the sender the size of the window.
  1. So how does the receiver tell the sender the size of the window?

In the TCP header, there is a 16-bit window size field, which stores information about the window size. The maximum number of 16 digits represents 65536 bytes, so the maximum number of TCP Windows is 65536 bytes? In fact, there is also a window enlargement factor M in the TCP header 40-byte option, and the actual window size is the value of the window field moved M bits to the left (moving one bit to the left equals multiplying by 2).

2.8. TCP congestion control

Congestion control boils down to TCP’s compromise of trying to send data to each other as quickly as possible without putting too much strain on the network.

  • TCP, with its sliding window killer, can send large amounts of data efficiently and reliably. But it can still cause problems if you start sending a lot of data. Because there are many computers on the network, the current network state is probably congested. Sending large amounts of data without knowing the current state of the network is likely to make things worse.

  • TCP, therefore, uses a slow start mechanism to send a small amount of data to explore the current network congestion, and then decide how fast to transmit data.

2.8.1 Congestion Window

  • When sending starts, define the congestion window size as 1;
  • Each time an ACK response is received, the congestion window increases by 1;
  • Each time a packet is sent, the congestion window is compared with the size of the window reported by the host at the receiving end, and the smaller value is taken as the actual window
  • When TCP starts, the slow start threshold is equal to the maximum window value
  • On each timeout retransmission, the slow start threshold is halved and the congestion window is set back to 1
  • Congestion Windows like the one above grow exponentially. “Slow start” just means slow at first, but it grows very fast. In order not to grow so fast, a term called the slow start threshold is introduced here. When the size of the congestion window exceeds this threshold, it does not grow exponentially, but linearly.
  • A small amount of packet loss, we just trigger timeout retransmission;
  • A lot of lost packets, we think of network congestion;
  • When TCP communication starts, the network throughput increases gradually.
  • As congestion occurs on the network, throughput immediately decreases.

3. The UDP protocol

3.1 Differences between TCP and UDP

Compare the item TCP UDP
Connection-oriented or not connection-oriented Oriented disconnection
Transmission reliability reliable unreliable
applications Transfer large amounts of data A small amount of data
Transmission speed slow fast
  • TCP provides a connection-oriented, reliable byte stream service. Connection-oriented means that two applications that use TCP as the transport layer protocol must establish a TCP connection before exchanging data with each other. TCP provides reliable transmission services for upper-layer applications through mechanisms such as confirmation, verification, and reorganization. However, the establishment, verification and verification of TCP connections require a lot of work and will bring a lot of overhead.

  • UDP provides a simple, datagram oriented service. UDP does not guarantee reliability, that is, packets cannot reach the destination. UDP is suitable for applications that focus more on transmission efficiency, such as SNMP and Radius. SNMP monitors the network and sends alarm messages intermittently. If a small number of messages are sent each time, a TCP connection needs to be established, which reduces transmission efficiency. UDP is the preferred transport layer protocol for more efficient applications such as SNMP and Radius. UDP also applies to application-layer protocols that have their own reliability mechanism.

3.2 Introduction to UDP

  1. UDP features:
  • UDP provides connectionless services for applications. The source and destination end do not need to establish a connection before data transmission.
  • There is no need to maintain connection state, send and receive state, etc., so the server can transmit the same message to multiple clients simultaneously.
  • UDP applies to applications that require high transmission efficiency.
  1. UDP header format

    UDP and TCP use IP as the network layer protocol. The TCP datagram is encapsulated in an IP packet. Unlike TCP, UDP does not provide reliable transmission. Therefore, THE UDP packet format is relatively simple.

As shown in the UDP header format above, the following table gives a brief introduction to the field meanings:

field role instructions
16-bit source port number A source port number assigned to a source-side application
16-bit destination port number Port number of the destination application
16-bit UDP length Indicates the length of the UDP header and UDP data in bytes. The minimum value of this field is 8
16-bit UDP checksum This field provides the same functionality as TCP validation and except that it is optional in UDP

4 IP

4.1 IP Packet Data Format

  1. The structure of IP packet is as follows: After receiving the TCP data segment of the transport layer, the network layer adds the IP header of the network layer. The normal IP header is fixed in length of 20 bytes (excluding the IP option field). The IP packet header consists of the following fields: The packet length is the number of 32-bit digits, including any options. Since it is a 4-bit field, 24=16, there are 15 valid bit fields excluding all 0 entries, and the maximum value is also 15, indicating that the header has 15 32 bits. So 32*15/8=60 bytes, the longest header is 60 bytes.

    The following table gives an introduction to the above fields:

field role instructions
Version Number The field indicates the IP protocol version number. The current protocol version number is 4. The version number of the next-generation IP protocol is 6.
8-bit Service Type (TOS, Type of Service) The fields include a 3-bit priority field (COS, Class of Service), a 4-bit TOS field, and a 1-bit unused bit. 4-bit TOS represents the minimum delay, maximum throughput, maximum reliability, and minimum cost respectively.
Total Length (Total length) Is the entire IP datagram length, including the data portion. Since this field is 16 bits long, IP datagrams can be up to 65535 bytes long. Although it is possible to transmit an IP datagram up to 65535 bytes, most link layers fragment it. Also, the host is required not to receive datagrams larger than 576 bytes. UDP limits the user datagram length to 512 bytes, less than 576 bytes. In fact, most current implementations (especially those that support the network file system NFS) allow IP datagrams larger than 8192 bytes.
Identification Field uniquely identifies each packet sent by the host. It is usually incremented by 1 each time a message is sent
TTL (Time to Live) Field sets the number of routers the packet can pass through. Once passed through a router, the TTL value is reduced by 1, and when the value of this field is 0, the packet is discarded.
agreement The protocol field identifies the upper-layer protocol to be transmitted in the packet. Similar to the port number, the IP protocol identifies the upper-layer protocol by the protocol number. The TCP protocol number is 6, and the UDP protocol number is 17.
Head checksum Field Computes the checksum of the IP header to check the integrity of the packet header.
The source IP address Field Identifies the source device of the packet
Destination IP address Field Indicates the IP address of the destination device
IP options
  1. Ethernet frame format Ethernet frame

    The Ethernet header is composed of three fields: DMAC, SMAC, and L/T(LENGTH/TYPE field).

  • Field description of Ethernet header:
field role instructions
DMAC MAC address of the destination terminal.
SMAC Indicates the source MAC address
LENGTH/TYPE field The value has different meanings: When LENGHT/TYPE is greater than 1500, it indicates the TYPE of the data frame (such as the upper-layer protocol TYPE). Common protocol types are as follows: 0X0800 IP packet 0X0806 ARP request/reply packet 0X8035 RARP request/reply packet. When LENGTH/TYPE is less than 1500, it indicates the LENGTH of the data frame.

5. The HTTP protocol

5.1 introduction of HTTP

HTTP stands for HyperText Transfer Protocal. The most significant feature of HTTP connection is that each request sent by the client requires a response sent back by the server. After the request is complete, the server releases the connection. The process from establishing a connection to closing a connection is called one connection.

5.2 introduction of HTTPS

Secure Hypertext Transfer Protocol (HTTPS) is a Secure communication channel. HTTPS is HTTP over SSL/TLS. HTTP is an application-layer Protocol, and TCP is a transport layer Protocol. Added a secure socket layer SSL/TLS:

  • Secure Socket Layer (SSL)

  • TLS (Transport Layer Security)

  • SSL uses 40-bit keywords as the RC4 stream encryption algorithm

  • Function:

A. Content encryption establishes an information security channel to ensure the security of data transmission; B. Identity authentication verifies the authenticity of a website. C. Data integrity Prevents content from being impersonated or altered by third parties

5.3 Differences between HTTPS and HTTP

Compare the item HTTP HTTPS
Whether to apply for a certificate from the CA Don’t need Need to be
Default port number 80 443
Whether information is encrypted Hypertext transfer protocol. Information is transmitted in clear text Is a secure SSL encrypted transport protocol
Stateful or not It’s stateless HTTPS is a network protocol that uses SSL and HTTP to encrypt transmission and authenticate identity. It is more secure than HTTP.

5.4 HTTP Status Code

  • A 2 header (request successful) indicates that the request’s status code was successfully processed.
HTTP protocol status code meaning instructions
200 successful The server has successfully processed the request. Typically, this means that the server has provided the requested web page
201 Has been created The request succeeds and the server creates a new resource
202 Have accepted The server has accepted the request but has not yet processed it
203 Unauthorized information The server has successfully processed the request, but the information returned may come from another source
204 There is no content The server successfully processed the request, but did not return anything
205 Reset the content The server successfully processed the request, but did not return anything
206 Part of the content The server successfully processed some of the GET requests
  • A 3 header (the request was redirected) indicates that further action is required to complete the request. Typically, these status codes are used for redirects.
HTTP protocol status code meaning instructions
300 A variety of options The server can perform a variety of actions on a request. The server can select an operation based on the requester (User Agent) or provide a list of operations for the requester to select
301 A permanent move The requested page has been permanently moved to the new location. When the server returns this response (a response to a GET or HEAD request), it automatically forwards the requester to the new location
302 Temporary mobile The server currently responds to requests from web pages in different locations, but the requester should continue to use the original location for future requests
303 Look at other locations The server returns this code when the requester should use a separate GET request for a different location to retrieve the response
304 unmodified The requested page has not been modified since the last request. When the server returns this response, the web page content is not returned
305 Using the agent The requester can only access the requested web page using a proxy. If the server returns this response, it also indicates that the requester should use a proxy
307 Temporary redirection The server currently responds to requests from web pages in different locations, but the requester should continue to use the original location for future requests
  • These status codes indicate that the request may be in error, preventing the server from processing it.
HTTP protocol status code meaning instructions
400 Bad request The server does not understand the syntax of the request
401 unauthorized The request requires authentication. The server may return this response for a web page that requires login
402
403 ban Server rejects request
404 Not found The server could not find the requested page
405 Method to disable Disables the method specified in the request
406 Don’t accept The requested web page cannot be responded to using the requested content properties
407 Agency authorization is required This status code is similar to 401 (unauthorized), but specifies that the requester should authorize the use of the agent
408 The request timeout The server timed out while waiting for a request
409 conflict A server conflict occurred while completing a request. The server must include information about the conflict in the response
410 deleted The server returns this response if the requested resource has been permanently deleted
411 Required effective length The server will not accept requests that do not contain a valid content-length header field. (Inconsistent packets)
412 Prerequisites are not met The server did not meet one of the prerequisites that the requester set in the request
413 Request entity too large The server could not process the request because the request entity was too large for the server to handle
414 The requested URI is too long The requested URI (usually a web address) is too long for the server to process
415 Unsupported media types The format of the request is not supported by the requested page
416 The requested scope is invalid If the page cannot provide the requested scope, the server returns this status code
417 Unsatisfied expected value The server did not meet the requirements for the “expected” request header field
  • These status codes indicate that an internal error occurred while the server was trying to process the request. These errors may be server errors rather than request errors.
HTTP protocol status code meaning instructions
500 Server internal error The server encountered an error and could not complete the request
501 Not yet implemented The server does not have the capability to complete the request. For example, the server may return this code if it does not recognize the request method
502 Bad gateway The server, acting as a gateway or proxy, received an invalid response from the upstream server
503 Service unavailable The server is currently unavailable (due to overloading or downtime for maintenance). Usually, this is a temporary state
504 Gateway timeout The server acts as a gateway or proxy, but does not receive requests from the upstream server in time
505 The HTTP version is not supported The server does not support the HTTP protocol version used in the request

6. socket

6.1 introduction of socket

Socket is a communication channel established to achieve the above communication process. Its real representative is a communication process between the client and the server. Both processes communicate through socket, and the communication rules adopt the specified protocol. Socket is a connection mode, not a protocol, socket is the TCP/IP protocol encapsulation, socket itself is not a protocol, but a call interface (API), we can use TCP/IP protocol through socket. TCP and UDP are simply (though inaccurately) the two most basic protocols, and many other protocols are based on them. For example, HTTP is based on TCP. Socket can be used to create TCP connections as well as UDP connections, which means that sockets can be used to create connections for any protocol, since all other protocols are based on it.

6.2 characteristics of the socket

socket advantages disadvantages
socket Data transmission is byte level, data transmission can be customized, small amount of data (for mobile applications: low cost) The transmitted data needs to be parsed and converted into application-level data
socket Short data transmission time and high performance The development level of the developers is high
socket It is suitable for real-time information exchange between client and server Compared with Http protocol transport, increased development
socket Can be encrypted, strong data security

6.3 Socket Comparison with HTTP

6.4 Socket Connection Establishment Process

  • The TCP three-way handshake to establish a connection and four-way handshake to disconnect a connection has been described earlier. Here the socket establishment and disconnection start is the code implementation of this process.

  • Review the TCP three-way handshake

    1. First handshake: The client attempts to connect to the server and sends a SYN packet with syn= J. The client enters the SYN_SEND state and waits for the server to confirm

    2. Second handshake: The server receives and acknowledges a SYN packet (ACK = J +1) from the client and sends a SYN packet (ACK = K) to the client. At this time, the server enters the SYN_RECV state

    3. Third handshake: After receiving the SYN+ACK packet from the server, the client sends an ACK packet (ACK = K +1) to the server. After the packet is sent, the client and the server enter the ESTABLISHED state to complete the three-way handshake

Flow chart:

  • The TCP three-way handshake also defines a socket three-way handshake, perhaps in reference to the TCP three-way handshake, some computer experts have drawn a model of the socket three-way handshake

  • Socket Process for establishing a client connection

(1) Open a communication channel and connect it to a specific port of the host where the server is located; (2) Send service request messages to the server, wait and receive the response; Keep making requests…… (3) After the request ends, the communication channel is closed and terminated.

  • Socket Process for establishing a connection to the server

(1) Open a communication channel and inform the local host that it is willing to receive customer requests on a certain port (such as FTP port 21) at a recognized address; (2) Wait for the customer request to arrive at the port; (3) When receiving the service request from the client, process the request and send the reply signal. When a concurrent service request is received, a new process is activated to handle the customer request (e.g., fork, exec on UNIX systems). The new process processes this customer request and does not need to respond to other requests. When the service is complete, the communication link between the new process and the customer is closed and terminated. (4) Return to step (2) and wait for another customer request. (5) Shut down the server

6.5 Socket connection code implementation

6.5.1 Client Code

  • Swift code
 dispatch_sync(dispatch_get_global_queue(0.0), ^ {// A block of code that handles time-consuming operations...
        
    
    / / create a socket
    /* AF_INET: ipv4 execution version of the IP protocol. 2.SOCK_STREAM: specified Socket type, connection-oriented streaming Socket transport layer protocol. 3. IPPROTO_TCP Transfer mode TCP transfer protocol The return value is greater than 0. Creation success */
    _clientSocket = socket(AF_INET.SOCK_STREAM.IPPROTO_TCP);

    // Establish a connection (with the server)
    Netcat nC-LK 12345 netcat NC-LK 12345 netcat NC-LK 12345 netcat NC-LK 12345 Sizeof (struct sockaddr) int -1 failure 0 success */
    struct sockaddr_in addr; / * to fill outsockaddr_inStructure * /addr.sin_family = AF_INET;
    addr.sin_port=htons(8080);
    addr.sin_addr.s_addr = inet_addr(" 192.168.0.99 ");int connectResult = connect( _clientSocket, (const struct sockaddr*) &addr.sizeof(addr)); // Send data (to the server) /* The first argument specifies the sender socket descriptor; The second parameter specifies a buffer to hold the data the application wants to send; The third parameter specifies the actual number of characters to send; The fourth argument is usually set to 0. Returns the actual number of characters sent on success, and -1, */ on failurechar * str="itcast";
    ssize_t sendLen = send( _clientSocket.str.strlen(str), 0); // Fetch data (from the server) /* The first argumentsocketThe second parameter is the size of the data buffer and the third parameter is the size of the buffer. The fourth argument specifies how to call, usually 0 returns the number of characters successfully received */char *buf[1024].ssize_t recvLen = recv( _clientSocket.buf.sizeof(buf), 0);
    NSLog(@ "-- - > %ld",recvLen); }); / / /self test];
}
Copy the code
  • C language code
#include<stdio.h>  
#include<stdlib.h>  
#include<netinet/in.h>  
#include<sys/socket.h>  
#include<arpa/inet.h>  
#include<string.h>  
#include<unistd.h>  
#define BUFFER_SIZE 1024  
  
int main(int argc, const char * argv[])  
{  
    struct sockaddr_in server_addr;  
    server_addr.sin_family = AF_INET;  
    server_addr.sin_port = htons(11332);  
    server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");  
    bzero(&(server_addr.sin_zero), 8);  
  
    int server_sock_fd = socket(AF_INET, SOCK_STREAM, 0);  
    if(server_sock_fd == - 1)  
    {  
    perror("socket error");  
    return 1;  
    }  
    char recv_msg[BUFFER_SIZE];  
    char input_msg[BUFFER_SIZE];  
  
    if(connect(server_sock_fd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr_in)) == 0)  
    {  
    fd_set client_fd_set;  
    struct timeval tv;  
  
    while(1)  
    {  
        tv.tv_sec = 20;  
        tv.tv_usec = 0;  
        FD_ZERO(&client_fd_set);  
        FD_SET(STDIN_FILENO, &client_fd_set);  
        FD_SET(server_sock_fd, &client_fd_set);  
  
       select(server_sock_fd + 1, &client_fd_set, NULL.NULL, &tv);  
        if(FD_ISSET(STDIN_FILENO, &client_fd_set))  
        {  
            bzero(input_msg, BUFFER_SIZE);  
            fgets(input_msg, BUFFER_SIZE, stdin);  
            if(send(server_sock_fd, input_msg, BUFFER_SIZE, 0) = =- 1)  
            {  
                perror("Error sending message! \n"); }}if(FD_ISSET(server_sock_fd, &client_fd_set))  
        {  
            bzero(recv_msg, BUFFER_SIZE);  
            long byte_num = recv(server_sock_fd, recv_msg, BUFFER_SIZE, 0);  
            if(byte_num > 0)  
            {  
            if(byte_num > BUFFER_SIZE)  
            {  
                byte_num = BUFFER_SIZE;  
            }  
            recv_msg[byte_num] = '\ 0';  
            printf("Server :%s\n", recv_msg);  
            }  
            else if(byte_num < 0)  
            {  
            printf("Error accepting message! \n");  
            }  
            else  
            {  
            printf("Server side exit! \n");  
            exit(0); }}}/ /}
    }  
    return 0;  
} 


Copy the code

6.5.2 Server-side code

#include<stdio.h>  
#include<stdlib.h>  
#include<netinet/in.h>  
#include<sys/socket.h>  
#include<arpa/inet.h>  
#include<string.h>  
#include<unistd.h>  
#define BACKLOG 5     // The length of the queue that completed three handshakes but did not accept
#define CONCURRENT_MAX 8   // The application layer can handle connections simultaneously
#define SERVER_PORT 11332  
#define BUFFER_SIZE 1024  
#define QUIT_CMD ".quit"  
int client_fds[CONCURRENT_MAX];  
int main(int argc, const char * argv[])  
{  
    char input_msg[BUFFER_SIZE];  
    char recv_msg[BUFFER_SIZE];  
    // Local address
    struct sockaddr_in server_addr;  
    server_addr.sin_family = AF_INET;  
    server_addr.sin_port = htons(SERVER_PORT);  
    server_addr.sin_addr.s_addr = inet_addr(" 127.0.0.1 ");bzero(& (server_addr.sin_zero), 8); / / createsocket  
    int server_sock_fd = socket(AF_INET.SOCK_STREAM, 0);  
    if(server_sock_fd == -1)  
    {  
        perror("socket error");  
        return 1;  
    }  
    / / bind socket
    int bind_result = bind(server_sock_fd, (struct sockaddr*) &server_addr.sizeof(server_addr));  
    if(bind_result == -1)  
    {  
        perror("bind error");  
        return 1;  
    }  
    //listen  
    if(listen(server_sock_fd, BACKLOG) = = -1)  
    {  
        perror("listen error");  
        return 1;  
    }  
    //fd_set  
    fd_set server_fd_set;  
    int max_fd = -1;  
    struct timeval tv; // Set the timeout periodwhile(1)  
    {  
        tv.tv_sec = 20;  
        tv.tv_usec = 0;  
        FD_ZERO(&server_fd_set);  
        FD_SET(STDIN_FILENO, &server_fd_set);  
        if(max_fd <STDIN_FILENO)  
        {  
            max_fd = STDIN_FILENO;  
        }  
        //printf("STDIN_FILENO=%d\n", STDIN_FILENO);  
    // Server-side socket
        FD_SET(server_sock_fd, &server_fd_set);  
       // printf("server_sock_fd=%d\n", server_sock_fd);  
        if(max_fd < server_sock_fd)  
        {  
            max_fd = server_sock_fd;  
        }  
    // Client connection
        for(int i =0; i < CONCURRENT_MAX; i++)  
        {  
            //printf("client_fds[%d]=%d\n", i, client_fds[i]);  
            if(client_fds[i] ! =0)  
            {  
                FD_SET(client_fds[i], &server_fd_set);  
                if(max_fd < client_fds[i])  
                {  
                    max_fd = client_fds[i];  
                }  
            }  
        }  
        int ret = select(max_fd + 1, &server_fd_set, NULL.NULL, &tv);  
        if(ret < 0)  
        {  
            perror("Select error \ n");  
            continue;  
        }  
        else if(ret == 0)  
        {  
            printf("Select timeout \ n");  
            continue;  
        }  
        else  
        {  
            //ret is the number of file descriptors whose state has not changed
            if(FD_ISSET(STDIN_FILENO, &server_fd_set))  
            {  
                printf("Send message: \n");  
                bzero(input_msg, BUFFER_SIZE);  
                fgets(input_msg, BUFFER_SIZE, stdin);  
                // Enter. Quit to exit the server
                if(strcmp(input_msg, QUIT_CMD) = =0)  
                {  
                    exit(0);  
                }  
                for(int i = 0; i < CONCURRENT_MAX; i++)  
                {  
                    if(client_fds[i] ! =0)  
                    {  
                        printf("client_fds[%d]=%d\n", i, client_fds[i]);  
                        send(client_fds[i], input_msg, BUFFER_SIZE.0); }}}if(FD_ISSET(server_sock_fd, &server_fd_set))  
            {  
                // There is a new connection request
                struct sockaddr_in client_address;  
                socklen_t address_len;  
                int client_sock_fd = accept(server_sock_fd, (struct sockaddr*) &client_address, &address_len);  
                printf("new connection client_sock_fd = %d\n", client_sock_fd);  
                if(client_sock_fd > 0)  
                {  
                    int index = -1;  
                    for(int i = 0; i < CONCURRENT_MAX; i++)  
                    {  
                        if(client_fds[i] == 0)  
                        {  
                            index = i;  
                            client_fds[i] = client_sock_fd;  
                            break; }}if(index >= 0)  
                    {  
                        printf("New client (%d) joined successfully %s:%d\n", index, inet_ntoa(client_address.sin_addr), ntohs(client_address.sin_port));  
                    }  
                    else  
                    {  
                        bzero(input_msg, BUFFER_SIZE);  
                        strcpy(input_msg, "The number of clients added to the server reached the maximum. \n");  
                        send(client_sock_fd, input_msg, BUFFER_SIZE.0);  
                        printf("New client failed to join %s:%d\n", inet_ntoa(client_address.sin_addr), ntohs(client_address.sin_port)); }}}for(int i =0; i < CONCURRENT_MAX; i++)  
            {  
                if(client_fds[i] ! =0)  
                {  
                    if(FD_ISSET(client_fds[i], &server_fd_set))  
                    {  
                        // Process a message from a client
                        bzero(recv_msg, BUFFER_SIZE);  
                        long byte_num = recv(client_fds[i], recv_msg, BUFFER_SIZE.0);  
                        if (byte_num > 0)  
                        {  
                            if(byte_num > BUFFER_SIZE)  
                            {  
                                byte_num = BUFFER_SIZE;  
                            }  
                            recv_msg[byte_num] = '\0';  
                            printf("Client (%d):%s\n", i, recv_msg);  
                        }  
                        else if(byte_num < 0)  
                        {  
                            printf("Error receiving message from client (%d).\n", i);  
                        }  
                        else  
                        {  
                            FD_CLR(client_fds[i], &server_fd_set);  
                            client_fds[i] = 0;  
                            printf("Client (%d) exited \n", i);  
                        }  
                    }  
                }  
            }  
        }  
    }  
    return 0;  
} 


Copy the code

7. Port

7.1. Introduction to Ports

Common default port number Network layer – There is an important field in the packet format called the protocol number. For example, at the transport layer the protocol number in the network layer IP packet will have a value of 6 if it is TCP and 17 if it is UDP – transport layer.

  • The transport layer-associated through interfaces (the fields of ports are called ports-is the application layer.
  • Use netstat -an to view port numbers that are open on the host.

7.2. Common Interfaces of the Server

  • The following ports are commonly used by proxy servers:
Server protocol The default port instructions
The HTTP protocol 80/8080/9080/3128/8081
SOCKS 1080
FTP File transfer protocol 21
Telnet Remote login protocol 23
The HTTP server The default port number is 80/ TCP Trojan Executor open this port
HTTPSsecurely transferring Web Pages server The default port number is 443/ TCP 443/udp
Telnet insecure text transfer The default port number is 23/ TCP Trojan Tiny Telnet Server
FTP The default port number is 21/ TCP opened by Doly Trojan, Fore, InvisibleFTP, WebEx, WinCrash, and Blade Runner
TFTP (Trivial File Transfer Protocol) The default port is 69/udp
SSH secure login, SCP file transfer, and port redirection The default port number is 22/ TCP
SMTP Simple Mail Transfer Protocol (E-mail) Default port number is 25/ TCP Trojan Antigen, EmailPassword Sender, Haebu Coceda, ShtrilitzStealth, WinPC, WinSpy all open this port
POP3 Post Office Protocol (E-mail) The default port number is 110/ TCP
WebLogic The default port number is 7001
Webshpere application The default port number is 9080
Webshpere management tool The default port number is 9090
JBOSS The default port number is 8080
TOMCAT The default port number is 8080
WIN2003 remote login The default port number is 3389
Symantec AV/Filter for MSE The default port number is 8081. The default port number of the Oracle database is 1521
ORACLE EMCTL The default port number is 1158
Oracle XDB XML The default database port number is 8080
Oracle XDB FTP service The default port number is 2100
MS SQL*SERVER Database SERVER The default port number is 1433/ TCP 1433/ UDP
MS SQL*SERVER database Monitor The default port number is 1434/ TCP 1434/ UDP
QQ The default port number is 1080/udp

8. webRTC

See my previous blog: Introduction to webRTC for more details

9. RTMP/RTSP protocol

See my previous blog for details:

  1. Knowledge of RTMP
  2. Knowledge of RTSP

Network packet capture tool

See my previous blog: Network Packet Capture Tools for more details

Alamofire framework

1. Introduction to the Alamofire framework