Steever in the first part of the STEVENS

zhaozj2021-02-11  162

I have been exiled into the countryside. I turned it when I was bored. I went out from the plate yesterday. I feel that I have never passed online. I have been buried. I am getting 9CBS. I don't want to laugh. I, I don't have to specify it.

Part 1: TCP / IP

==================== cEnt-Server concept: ===========================================================================================================================================================================

For example, WWW Server and browser, FTP Server and a wide range of FTP tools, and so on.

A particular service provides a specific service, running in the background, does not directly and user interaction interface, command line, etc., it responds to Client's service requests, and returns the data required by the client to client, of course, where is It may be necessary to pass the database operation or calculation.

The client is a client program that interacts directly with the user or operator, communicates with the remote server or the local background Server, completes the user's request. A Client can only communicate with a determined Server at any time, while Server can handle multiple clients.

Client-Server is a general mode to write a network program (in some cases, there may be more complex structures, such as one application makes both Server and custom).

The application's communication must pass the network protocol, only discussed TCP / IP protocols in this article.

This article does not stratify according to ISO's OSI seven-layer network, but the top three layers (application layers, representation layers, session layers) in the OSI structure are collectively referred to as the application layer, and the bottom two layers of the OSI structure (link) Layer, physical layer) Currently referred to the link layer. In this way, our hierarchical structure is:

┏┏━━━┯┯━━━━━━━━━━━━━━━┓┓ ┓ Application │ and the application and service of the user interaction ┠────────────────────────────────────────────── ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ IPv4 & IPv6 ┠ - ─────────────────────────────────── ─ ┨ ┨ 程序 程序 程序, 卡 卡 ━ ━ ━ ┗ ┷┷━━━━━━━┛━━━━━━

Client and Server do not have to be in the same network segment, can be connected via a wide area network. Of course, the middle must pass the router.

============================, a daytime TCP client example: ================ =============

1 #include "unp.h"

2 INT3 main (int Argc, char ** argv []) 4 {5 int suckfd, n; 6 char recvline [maxline 1]; 7 struct sockaddr_in servaddr; 8 if (argc! = 2) 9 err_quit ("Usage: % S , Argv [0]);

10 IF ((Sockfd = Socket (AF_INET, SOCK_STREAM, 0) <0) 11 Err_sys ("Socket Error");

12 Bzero (& Servaddr); 13 servaddr.sin_family = af_INET; 14 servaddr.sin_port = htons (13); 15 if (INET_PTON (AF_INET, Argv [1], & servaddr.sin_addr) <= 0) 16 Err_quit ("INET_PTON Error For% S", Argv [1]);

17 IF (Connect (sockfd, (sa *) & servaddr, sizeof (servaddr)) <= 0) 18 err_sys ("connet error");

19 While ((n = read (sockfd, recvline, maxline)> 0) {20 recvline [n] = 0; 21 IF (FPUTS (RECVLINE, STDOUT) == EOF) 22 err_sys ("fputs error"); 23 } 24 if (n <0) 25 err_sys ("read error");

26 exit (0); 27}

The results after this program are roughly as follows:

# a.out 206.62.226.35fri jan 12 14:27:52 1999

There are many details in this 27-line program, let's take a look at:

1: unp.h is our own header file, there are some macro definitions, and some incrude statements.

2 - 3: Command line parameters

10 - 11: Create a TCP Socket, the so-called TCP Socket, is actually an Internet (AF_INET) STREAM (Sock_Stream) Socket, pay attention to the uppercase of the Internet, such a writing refers to the interconnected network, not the Internet; stream The meaning of byte stream. In contrast, SOCK_DATAGRAM, SOCKET of the datagram, namely: UDP.

12 - 16: Fill in the address structure of the socket, fill in the IP address of the Server side and the port number to which you want to connect (port_number). We first set the content of the entire structure into 0 through Bzero, put the address family address family as: AF_INET, the address family is a parameter that the kernel needs, although our programs use AF_INET, but in fact the kernel can handle multiple kinds Address structure, a typical example is: AF_UNIX, limited to Socket address structures between local processes. The port number is the port number of our needs, in this example, the port of Daytime: 13, the IP address is the parameter value of the command line, and these values ​​in this address structure have a specific format, so we The library function: htons: host to network short and inet_pton: presentation to numeric to convert format. Note: For some early IPv4, inet_pton is not supported: inet_addr. 17 - 18: Connect calls the connection to the IP & Port specified in the ServAddr structure, pay attention to the third parameter of Connect, which is the size of the servadDR structure, which is also necessary for the kernel to handle multiple address structures. #Define sa struct sockaddr_in This kind of write does not make the program line out.

19 - 25: Read the return and output to the screen (stdout). It should be noted here that since the TCP is a character stream protocol, the string returned by the server may be in a TCP Segment, which may be within a variety of TCP segments, so we read data from the TCP socket. It always puts the read in the loop until the READ returns 0 (the other party turns down the socket) or returns the number of less than 0 (Error). In this example, because Server closes its socket so that the READ in our program returns 0, this form also exists in HTTP; but there are other protocols, such as ftp and SMTP, is at each record tail The label is launched, and there is a situation, which is the length of this record first in each recording head, the Sun RPC and DNS are like this. Finally, the TCP itself does not provide a service of the recording boundary. If the application needs to know if a record is end, it must find a way, such as the above three.

26: The program ends. Unix closes all file handles that do not close, including sockets.

There are too many things, come slowly, no hurry.

========== The protocol is independent ==========

The above program is based on IPv4, if we want it to work under IPv6, we have to do the following changes:

7 struct sockaddr_in6 servaddr;

10 IF ((SOCKFD = Socket (AF_INET6, SOCK_STREAM, 0) <0) 13 servaddr.sin6_family = AF_INET6;

14 servaddr.sin6_port = htons (13);

15 IF (inet_pton (AF_INET6, Argv [1], & servaddr.sin6_addr) <= 0)

That is, all places used in AF_INET or SERVADDR.SIN_ADDR. There will be a call: getaddrinfo call, let us write a program that is unrelated to the agreement.

People are always accustomed to saying: 169.xici.net.cn's HTTP service instead of: 10.74.32.74 80 port. So we have to convert domain names and services into system calls accepted, with such functions: gethostbyname and getServByname.

======== error handling ========

We can't write this case every program:

IF ((SockFD = Socket (AF_INET, SOCK_STREAM, 0) <0) Err_sys ("Socket Error");

We like this:

INTSOCKET (INT Family, Int Type, INT Protocol) {INT N;

IF ((N = Socket (Family, Type, Protocol) <0) {Err_sys ("Socket Error");

Return n;

The purpose of this is to make the program look still less.

Each time the system calls an error, the system call returns -1, UNIX's global variable errno is assigned, and its value has a detailed description in .

============================ 一 dTime TCP Server example: =============== =============

We come from users to write a Server:

1 #include "unp.h" 2 #include

3 INT4 main (int Argc, char ** argv []) 5 {6 int Listenfd, connfd; 7 struct sockaddr_in servaddr; 8 char buff [Maxline]; 9 TIME_T TICKS;

10 listenfd = socket (AF_INET, SOCK_STREAM, 0);

11 bzero (& servaddr, sizeof (servaddr)); 12 servaddr.sin_family = AF_INET; 13 servaddr.sin_addr.s_addr = htons (INADDR_ANY); 14 servaddr.sin_port = htons (13); 15 Bind (listenfd, (SA *) & servaddr SIZEOF (SERVADDR));

16 listen (listenfd, Listenq);

17 for (;;) {18 connfd = accept (listenfd, (sa *) null, null);

19 Ticks = Time (NULL); 20 snprintf (buff, sizeof (buff), "%. 24S / R / N", CTIME (& Ticks)); 21 Write (Connfd, Buff, Strlen);

22 Close (Connfd); 23} 24}

11 - 15: By filling out the address structure and calling Bind, the port 13 and the listenfd are bound; INADDR_any means that listenFD is allowed to accept any address connection request, if we don't want to, we can specify that listenfd can accept request. address. Then discuss it.

16: Call Listen, Listenfd enters the Listening status, Listenq is to tell the kernel how big a queue can be opened for the connection request, and the maximum value is generally 5.

17 - 21: Accept is a blocking call, the program is executed here, stop, wait for the connection request, when the connection request arrives, and the TCP's three-segment handshake is complete, return, return a new file handle: connfd, for each Different connections, Accept returns different connfds, unlike Listenfd, Listenfd is only waiting for the connection request, and the connection to each already implemented, we use this Connfd to communicate, exchange data. Snprintf is to prevent malicious attacks, if you use sprintf, a large number of service requests can easily lead to cache overflow, similar to this similar to: Gets, Strcat, Strcpy, usually: fgets, strncat, strncpy Instead.

Also, this program is also related to the agreement, and we can also use GetDrinfo to make it independent of the agreement.

This server can only handle a service request at the same time, in the process of processing this request (although this time is very short) cannot accept new requests, in order to process the client's service request, we have to use UNIX system calls: fork Create a child process for each connection. After processing the sub-process nature, there is another way to generate many sub-processes in advance. After processing, it can be recycled, and the latter is generally not common.

If we want to make this Server run in the background, we generally change some code to cooperate with the SuperServer: inetd under UNIX, this will be said later. We can now simply use & put it in the background. Of course, if you want to run, the port cannot be used 13, which has been used in the system of authentic Daytime Server, we have to change one. ======== Common command ========

NetStat, ifconfig, ping is the most commonly used commands that check the network status. You can view the MAN online document to get detailed usage.

The general usage is:

Netstat

-i: View network interface, such as: LO0, ETH0-R: View Routing Table -a: View All Socket Status - N: Displayed in digital form

Ifconfig

After the interface name defined in the system, check the interface details

ping

The back is followed by the IP address, through the ICMP protocol, check the network's connectivity; can also understand the operation of the host in a network segment by broadcasting addresses; can check the size of the line through -s to specify the size of the ICMP package.

====== IP introduction ======

The IP layer provides a non-confirmed datagram transmission service. The IP layer has made the best efforts to send datagrams to the destination, but does not guarantee the completeness of the data, the reliability must be completed by the upper protocol, such as TCP If you use UDP, you are responsible by the application yourself.

Core content of the IP layer: segmentation, reload, inter-network relay, and routing.

IPv4 structure: (IPv6 Even if it is, there is a lot of things, it is still not fixed)

0 3 4 7 8 15 16 31 ┏┏━┯┯┯━━┯┯━━━━━━┯┯┯━━━┓──━━━── ──│ header │ type of service│ total length (in bytes) ┃ ↑ ┃ (4) │ length │ │ ┃ │ ┠────┴────┴────────┼─┬─┬─┬ ──────────┨ │ ┃ identification │0 │DF│MF│ fragment offset ┃ ┠─────────┬────────┼─┴─┴─┴ ───────── ─ ┨ 20 T │ protocol │ header checksum Bytes ┠ - ─────────────────────── ─ ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── ──────── ─ ─ ─ ─ ────────────────────────────────────────────────────────────────────────────────────────────────────────── ─ ─ ─ ─ ─ ─ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── ─ ┨ ┋ ┋ ┋ Data ┋ ┋ ┋┋┗━━━━━━━━━━━━━━━━━━━━━━┛┛┛┛┛┛┛

Version: 4-bit version number, value is 4 (IPv4)

Header Length: The length of the entire IP header, including options (Options), the unit is four-byte (32-bits), because this domain is 4 bits, the maximum value is 15, so the maximum length of the IP head is: 60 words In section, this 60 bytes include 20 bytes of fixed headers, 40 bytes of options.

Type of Service: 8-bit service type field, consisting of three first mailing (unfained) and four service types and a reserved bit (must be 0), we can set the service type through the socket IP_TOS option: requirements Try to be highly transferred as small delays, or as much reliability as much as possible.

Total Length: 16-bit, the length of the entire IP package, including the head, we can calculate, the actual load length is the value of the value of four times the value of the Header Length of the value of this field. The role of this field is: The usual link layer has a minimum data frame length, such as the 802.3 network has a 64-byte limit (computer network 213-214), there is a legal IP package You cannot meet this request, the local link layer will add a fill field to meet the physical needs, the remote link layer will give these fill fields to its IP layer, the other party IP layer will use this length value to determine The length of valid data. Identification: 16 bits, gives different values ​​for each IP package, used to segment, reload.

DF & MF: Do Not Fragment, and More Fragment Meaning, these two bits and the 13-bit Frag- Ment Offset are used for segmentation and reloading.

Time to Live: Assignment by the sender, in the process of datagram delivery, by each router is reduced, once this value is reduced to 0, the datagram is discarded, the maximum value of this field is 255, the default value is general Is 64, we can set its value via the socket IP_TTL and IP_MULTICAST_TTL options.

Protocol: Indicates the protocol used in the payload field in the IP package: 1 (ICMPv4), 2 (IGMPv4), 6 (TCP), 17 (UDP), and more.

Header Checksum: Head (including optional option) checksum.

Address: Source and destination IP address.

Options: Some routing, timestamp, security information. Maximum 40 bytes. You can read and set up through the ipproto_ip, ip_options of GetSockopt, SetsockOpt.

With regard to the representation of the IP address, we use: 206.62.226.67/26 to represent the host 206.62.226.67, its mask is: 255.255.255.192 (26 1), the network address of this network segment is: 206.62.226.64/26 The broadcast address is: 206.62.226.127. We no longer pay the classification of the so-called A, B, and Class C.

Loop address: Any IP package sent to address 127/8 is not sent to the link layer, but directly as input for local IP layers; usually with this address to debug the program, macro definition: INADDR_LOOPBACK 127.0.0.1 ( This most commonly used).

MultiHomed Host definition: 1. Hosts with multiple interfaces, such as two 802.3 network cards (can be in the same network segment), or an 802.3 network card and a .25 network card, or an 802.3 network card and a dial-up backup line. 2. Use different IP addresses on the same interface. (I don't understand this, I have not paid)

=========== iCMPv4 Introduction =========== ICMP: Internet Control Message Protocol

ICMP is built on the IP, used to transfer errors and control information between host, router, usually used by TCP / IP software itself, but there are also applications using ICMP, such as: ping, traceroute.

0 7 8 15 16 31 ┏┏━━━━━━┯┯┯━━━━━━┯┯━━━━┓┓━━━━━━━━┓┓┓ ┓ │ CODE │ Checksum Ou ┠─────────────────────────────────────────────────── ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┋ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━┛━━━━━

What I have to care is what ICMP messages can I get, what information indicates what errors, the error reason is how to return to our programs:

┏┏┯┯┯┯┯┯━━━━━━━━━━━━━━┯┯┯━━┓━━━━━━━━┓┓┓┓┓━━━━━━┓┓┓pp━━━━━┓┓pppp━p━ │ │ Handled By OR Errno ┠ - ┼────────────────────────────────────────── ─ ─ │ 0 │ Echo reply │ User Process (ping) ┠, ┼──────────────────────────────────────────────── ─ ─ │ │ │ Destination unreachable:

│ ┃┃ │ │ │ ┃┃ │ 0 │ network unreachable │EHOSTUNREACH ┃┃ │ 1 │ host unreachable │EHOSTUNREACH ┃┃ │ 2 │ protocol unreachable │ECONNREFUSED ┃┃ │ 3 │ port unreachable │ECONNREFUSED ┃┃ │ 4 │ fragmentation needed │ EMSGSIZE ┃┃ │ │ but DF bit set │ ┃┃ │ 5 │ source route failed │EHOSTUNREACH ┃┃ │ 6 │ destination network unknown │EHOSTUNREACH ┃┃ │ 7 │ destination host unknown │EHOSTUNREACH ┃┃ │ 8 │ source host isolated (obsolete │ 9 │ Destination Network│ │ │ │ Administrative ProhibIn │ ┃┃ │ 10 │ destination host │EHOSTUNREACH ┃┃ │ │ administratively prohibited │ ┃┃ │ 11 │ network unreachable for TOS │EHOSTUNREACH ┃┃ │ 12 │ host unreachable for TOS │EHOSTUNREACH ┃┃ │ 13 │ commuication administratively │ ┃┃ │ │ PROHIBITED │ │ │ Host Precedence Violation │ ┠ - ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ──────────────────── ┨┨ 4 │ 0 │ Source quench │kernel for tcp │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │

│IGNORED BY UDP ┠ - ┼ - ┼────────────────────────────────────────────────────── ─ │ │ │ │ │ 0 │ d d │kernel Updates Routing Table │ 1 │ Redirect for Host │kernel Updates Routing Table │ 2 │ Redirect for Tos and Network │kernel Updates Routing Tablewry Table │ 3 │kernect for Tos and host │kernel Updates Routing Tab ─ ─ ─ ───────────────────────────────────── ─ ┨ ┨ 8 │ 0 │ Echo Request │kernel generates reply ┠ - ┼─┼─────────────────────────────── ───── ─ ┨ 9 │ 0 │ Router Advertisement │USER Process ┠ - ┼ - ┼────────────────────────────────────────────────────────── ─ ─ ─ ┨ ┨ │ 0 │ Router Solicitation │USER Process ┠ - ┼ - ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── ───────── ┨ │ │ Time Exceeded: │ 10 │ │ │ q ──────────────────────────────────────────────────────────────────────────────────────────────────────────────> ─ ─ ─────────────────────────────────────────────────── │ │ │ b (catchaall error) │1 │ 1 │ Required Option Missing│ ┼─────────────────────────────────────────────── ─ ─ ─ ┨ │ 0 │ Timestamp Request │kernel generates reply ┠ - ┼ - ┼────────────────────────────────────── ─ ─ ─ ─ ─ ─ ─ ─ │ 0 │ TimeStamp REPL

Y │User Process ┠ - ┼ - ┼──────────────────────────────── ─ ─ ─ ┨ ┨15 │ 0 │ Information Request (ibsolete) │ (Ignored) - ─ ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── 16 │ 0 │ information reply (obsolete) │USER Process ┠ - ┼────────────────────────────────── ─ ─ ┨ ┨17 │ 0 │ address mask request │kernel generates reply ┠ - ┼─ ──────────────────────────────── ────── ─ ┨┨18 │ 0 │ address mask reply │USER Process ┗┷┷┷┷┷┷━━━━┷━━━┷┷━━━━━━━┷┷ ━━━━━┛┛ All Note: User Process, you can get it through Raw Socket (original socket).

Original socket: Socket: SOCK_RAM directly facing the IP layer.

================ TCP / IP protocol introduction =================

The most important two protocols in the TCP / IP protocol are both: TCP and IP, in addition to UDP, ICMP, IGMP, ARP, RARP, BPF, DLPI.

ICMP we have already introduced, and the following is simple to say several other protocols:

IGMP: Internet Group Message Protocol for multi-point broadcasting.

ARP: Address Resolution Protocol, the mapping relationship of the IP address and the physical address of the link layer, only when the link layer is a broadcast form, such as: 802.3 (Ethernet), 802.4 (Token Bus), 802.5 (Token Ring), FDDI, etc., do not need to point to point-to-point connections.

Rarp: Reverse Address Resolution Protocol, implements mapping from the link layer physical address to IP addresses, usually used for startup processes for diskless workstations.

BPF: BSD Packet Filter DLPI: Data Link Provider Interface These two are the protocols of direct and link layers, only Linux provides a special name: SOCKET's socket can take advantage of these two protocols.

It is worth noting that in IPv6, ICMP, IGMP, ARP, and RARP are replaced by a protocol called ICMPv6, which is no longer IPv4, but IPv6.

=============== t t = ===============

These two protocols are the transport layer protocol in our five-story structure, and it is also the entry point of our Socket program, it is necessary to introduce, but it is not as good as you read. UDP: User DataGram Protocol, User Data News Agreement

Provide connectionless datagram services, that is, not guaranteed data delivery. It is just simply handed over the application's data to the IP layer, the IP layer packages the data into the IP package, sent to the destination, no confirmation! If necessary, the application must be responsible for handling confirmation, timeout, retransmission, flow control, etc.

Every UDP's datagram has a length, we can see it as a record, if the data is completely correct to reach the destination, the other party can know the length of the record, this point and TCP.

There is no advantage in the Client and Server, there is no connection to the transaction that is completed with a package, does not require a cumbersome three-stage handshake and four packages, the Client can send to a Server After the data is used, it is immediately sent to another Server. Similarly, the same socket of the Server can also sequentially receive different client data.

TCP: Transfer Control Protocol

The transmission control protocol provides connection-oriented, full-duplex, reliable, sequential, non-duplicated byte stream service, TCP protocol seizes the user data segmentation in units of maximum transmission length accepted by communication. The TCP protocol does not maintain the record boundary of the data; the TCP inside itself has a mechanism such as confirmation, timeout, retransmission, flow control.

Connection: To use TCP communication, you must first establish a connection before you can exchange data, and finally disconnect.

Reliability: When the TCP sends data to the other party, it will wait a confirmation. If it does not receive a confirmation, the TCP will retransmit it again, continue to wait for confirmation, after a certain number of retransmission, TCP will give up, and return an error message. There is an algorithm called RTT: Round-Trip Time, you can know when to confirm when to arrive, RTT, may be microseconds on a LAN, may be seconds on a WAN, and this value is Dynamic, at a moment, TCP thinks that RTT is one second, but after 30 seconds, TCP may think that RTT is two seconds, which is determined by the load at the time of the network, and TCP can calculate the next confirmation should wait for more time. It is usually sent from the first time to finally give up, it is 4 minutes to 10 minutes.

Orderation: TCP will numbered each byte tag for it. For example, the application is to send a 2k long data so that TCP is divided into two segments (so-called segment, the data unit of TCP is handed over to IP), then TCP gives the first segment number 1-1024, The number number of the second segment is 1025-2048, if the data is reached in order, or repeats (due to unnecessary retransmission), the other party's TCP will be arranged according to the number, discard the copy, and put the correct data Give it to the app,

Flow control: TCP always tells its other end, it is currently able to accept how many bytes of data, this value is called the active window, at any time, the value of the active window is always the current receiving buffer's idle sum, the value of the window Dynamic, when the data arrives, the window value is small, when the application reads, the window value is large, if the reception buffer is full, the application is not read, the window value is 0, at this time, when receiving any Before the data, you must wait for the program to take the current data from the buffer. Full duplex: The program can simultaneously receive and transmit data at the same TCP connection, and TCP reserves different movable window values, serial numbers, and the like for transmission of each direction. (UDP can also send and receive the same SOCKET)

___________________________________________________________

TCP connection establishment

TCP is based on the following four steps:

1. Server must be prepared to accept a connection request, via: Socket, Bind, Listen call, this process is called passive open (Passive Open).

2, the client is turned on (Active Open), which makes the TCP of the Client side sends a SYNCHRONIZE, telling Server, I (client) initial sequence number, usually this SYN segment does not contain any data, only IP header, TCP header, there may be TCP options (up to talk about).

3, Server gives a confirmation and gives the client a SYN segment, telling the CLIENT its initial serial number, and its TCP option (the options sent by the Client are usually different, all duplex), usually this ACK And SYN is sent in a segment.

4, Client confirms the SYN of Server.

Figure:

Client Server ConnecTry Syn J (Active Open) ┠ - ─ ─ ─ → ┨ ┨ PCEPT Ack J 1, SYN K nenect retURN ← ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── ─ ┨ ┨ 10 ──────────── → ┨ Accept return

Client's initial serial number is J, the initial serial number of Server is K, ACK J 1 means: I have received J, the next expectant J 1.

The J, K here is the serial number of the package. The M, N below is also the meaning. It is clear that the initial serial number of Cl-Int is j, the initial serial number of Server is K.

___________________________________________________________

TCP option

1, MSS: maximum segment size, maximum length, we can read or set it through the definition of TCP_MAXSEG, read or set it through getSockopt, setsockopt, usually this value is related to the maximum frame length of the link layer, by appropriate settings, Data segmentation can be reduced or prevented from being prevented. 2, the active window size, the maximum active window size recommended to the other end of the connection is 65535 bytes, because the width of this field is 16 bits in the TCP header, but only 65535, but in some speeds On the network (or a big place: satellite), this value is not enough, so the new definition is 14 bits left to the left, then the maximum is 65535 multiplied by 2, equals: 1073725440 words Festival, enough. In order to be compatible with the early TCP compatibility: TCP can propose its suggested window size, but it is only adjusted to your window when the other party also proposes this option. Macro Definition: SO_RCVBUF.

3, timestamp, timestamp, mostly used for high-speed network, in order to prevent false packet errors, programmers do not need to understand this.

___________________________________________________________

The release of TCP connections should pass through the following four steps:

1. First call one end of the Close (also called Active Close), send a TCP package with the FIN flag, indicating the end of the data transmission.

2. Receive one end of the FIN (also called: passive close), confirm the FIN package, and put it in the last end-of-file to the application's reception buffer; because it means that the FIN means this connection It is impossible to receive any data.

3. After a period of time, the application receives end-of-file, calls Close, and passively closes the TCP to send the FIN package.

4. After receiving the fin party, do confirmation.

As shown: We assume that it is a client to do Active Close.

Client Server Fin M CLOSE ┠ - ────── → ┨ ┨ ad Return 0 Ack M 1 ┠ ← ───────────────────────────── ─ ─ ┨ ┨ 10 N ┠ ← ─────────── ┨ ┨ 10/> ┠ - ───────── → ┨accept return

It usually requires four packages to completely release a TCP connection, but Fin M is sent along with the data, while the ACK M 1 and FIN N are sent together (the application has received end-of-filile, call Close).

After confirming M 1, before sending FIN N, there may be data from the Passive Close one party to the Active Close one, called: Half-Close, we will discuss in detail when you talk about ShutDown. ___________________________________________________________

TCP status

This thing is more important, because NetStat -a's last column shows some of this 11 state.

First we define the CLOSED status, which is the starting point of Socket, which is the end point. It is impossible to display in NetStat -a, because NetStat -a is not displayed with a closed Socket, we can think about this status, or You can also think that there is no such state.

A most common thing is the state of the ESTABLISHED, that is, the connection has been established and is using.

Since one of Active Open does not necessarily be Active Close, it may be Passive Close, so we separate Open and Close, first say the state in the OPEN process:

Active Open: Send SYN J to enter the SYN_SEND state from Closed, receive ACK J 1, SYN K, and send ACK K 1, enter the Established state.

Passive Open: After calling listen, enter: Listen status, send ACK J 1, SYN K, enter the SYN_RCVD status after receiving SYN J, and then enter the ACK K 1 to enter the Established state.

When disconnecting:

Active Close: After sending the FIN M, enter the FIN_WAIT_1 status, receive the ACK M 1, enter the FIN_WAIT_2 state, then receive the FIN N, send ACK N 1, enter the Time_WAIT state (this time_wait immediately).

Passive Close one: Receive the FIN M, send ACK M 1, enter the close_wait state, when the application calls the Close, send FIN N, enter the Last_Ack status, receive the last ACKN 1, return to the Closed state.

Here is a special case, that is, both parties calls Close, which is very common, because TCP does not keep the recording boundary, when a program uses the first transmission length to the other party to mark the record, often appear simultaneously to close SOCKET Situation: When the sending is sent, call the Close, receive the length first, then receive the length of the data specified, I don't want to close, and then, if I want to send a FIN, I haven't received ACK, I received a FIN. At this time, we call it: closing status, in this case, both sides must send, receive ACK, and finally enter time_wait.

Time_wait: Every time Active Close has to enter this state, what should you wait?

1, the one of Active Close also sent the last ACK party. If this ACK is lost, the other party will send FIN, it is to wait for this Not a reached FIN, if you don't wait, enter the closed, and ACK is really lost, then The other party will send FIN, but it will never receive the ACK, and the other party's application will receive an error. 2, waiting for all IP packages that are still on the way. We consider an extreme example, it is not impossible: we are on 206.62.226.63 FTP to 198.69.10.2, the local port number is temporary, we assume that it is 1500, then this connection is <206.62.226.63.1500 , 198.69.10.2.21>, this way to write, we will immediately say, at some point after this connection is established, a router or a line out of a problem, the delay is turned on, after Timeout, the package is returned The other party receives, then this time, turn off the connection, assume that there is no Time_Wait state, the local temporary port number 1500 is released, then there is another user connected to the 198.69.10.2 FTP port, its temporary port number is also 1500 So, this connection appears again: <206.62.226.63.1500, 198.69.10.2.21>, well, this time, when the line or the router is delayed, it is delayed, and an error, and

From the above two reasons, we can see that time_wait should be able to wait until that is not necessarily FIN, but also allow all IP packages on the way to eliminate death: should be 2MSL, MSL: Maximum segmentlifetime, is an IP package The maximum time of survival on the network, about this MSL, RFC 1122 is 2 minutes, while the BSD Socket is implemented for 30 seconds. This time is mainly determined by the TTL and some empirical value of the IP header.

If the ACK is lost during the time_wait, the last FIN that is resended is constantly lost until Time_Wait ends, then the other party's application will receive an error, but for this situation, we have no power.

After the Time_Wait time, enter the Closed status.

___________________________________________________________

TCP port number

We have to pay attention to so:

1. System retention port: 1-1023, only superuser's process can use ports in this range and its socket binding as a Server.

2. Temporary ports: 1024-5000, these are used by the local client process, and the system temporarily assigns the port numbers within this range. We have to pay attention to if our Server uses the port number within this range, then it does not necessarily run success at any time (it is possible in RC.D). This range is now very small, not enough, so Solaris moves its range to 32768-65535, and some versions of UNIX change the upper limit 5000 to 5000.

3, some Client processes must use retention port numbers, such as rlogin, RSH, which get a unused port number in 513-1023 through a call called RRESVPORT, this call starts a trial from a big value until encounter Not occupied, in general, 1023 is not occupied, that is, Rresvport is generally returned 1023. _____________________________________________________________

Socket Pair: It is this way of writing: <206.62.226.63.1500, 198.69.10.2.21> The number behind the IP address represents the local port number, which means a pair of Socket, which has four elements: local IP, local Port number, remote IP, remote port number, a socket pair is unique on its network, such as the Internet, which can identify a uniquely determined TCP connection.

Although UDP is not a connection-oriented protocol, we can also define udp socket pair, of course, this is not meaningful.

To understand the Socket Pair, we consider this situation: Server is a 198.69.10.2 ftpd process, which is bound to 21, then a user of 206.62.226.63 is established with this server, which is the temporary port number it obtained is 1500, at this time, there is a Socket Pair: <198.69.10.21, 206.62.226.63.1500>, then the problem came out, the port 21 on 198.69.10.2 is not in listen? What if the new connection request is coming? Revealing the source code of the Daytime, Socket used for Listen is listenfd, and the socket with the client communication is connfd, let's say: At 198.69.10.2, there is indeed two Socket: IP addresses The port number is the same, however, we determine that a TCP connection is a socket pair, so if there is a package of 198.69.10.2.21, the TCP core will check the source of the package, if it is 206.62.226.63.1500, Just send the package to the socket that has been established. If not, give it to the socket in listen. More extreme, if Server is concurrent (ftpd is indeed), generates a child process when processing the first connection, then from 206.62.226.63, it comes from 206.62.226.63, then it will open a child process. This Socket Pair is, for example,: <198.69.10.2.21, 206.62.226.63.1501>, then, in the future, the TCP core on 198.69.10.2 will check the source if it is 206.62. 226.63.1501, for the connfd of the second child process, if it is 206.62.226.63.1500, it is given to the CONNFD of the first child process. If it is not, it will be given to -Listenfd.

_____________________________________________________________

The physical restrictions of the IP layer and the impact on TCP: 1, IPv4 packs can not exceed 65535 bytes, including heads, because the length field is only 16 bits.

2, the IPv6 package can not exceed 65,575 bytes because its length field does not include 40 bytes of the head.

3, MTU: Maximum Transmission Unit, the maximum frame length determined by the link layer, Ethernet is 1500 bytes, and the PPP's MTU is negotiable, SLIP is 296 bytes, IPv4 requires minimitive link layers with a MTU value of 68 bytes, IPv6 is 576 bytes.

4, the smallest path, refers to the minimum MTU from all links from one host to another, now this value is typically 1500 bytes of the Ethernet. This path is minimal MTU, which is directionality, from the value from the A to B and the values ​​from B to A may not be the same, because the route may be different.

5. When IP is sent to a package in an interface than a small length of the current to send data, IP will segment the data, and these segmented data are not reloaded until the final destination is reached. For IPv4, hosts, and routers can be segmented, in IPv6, the router does not allow the package to be segmented to the package to be forwarded, but a simple return error message: Packet TOO BIG. (To illustrate, if it is the package generated by the router itself, such as generated by telnetd, because many routers are configured through the local area network, directly at the end is too trouble; these packages can be segmented by the router)

6. If "df" is set, the hosts and routers in IPv4 cannot segment the package, but return: Fragmentation NEeded But DF bit set ICMP package or error message. This feature of the DF bit is used to find the minimum path of the path, of course IPv6 can also do this, because its router cannot be segmented.

7, minimum reassembly buffer size, IPv4 is 576 bytes, IPv6 is 1500 bytes, we can't know if a given IPv4 host can receive a 577-byte package.

8, TCP MSS, has already said, here to point out, its value is generally the path minimum MTU minus TCP head length and IP head length, for example, the least path is 1500 bytes of Ethernet The MSS proposed by the TCP using IPv4 is 1460. If IPv6 is used, it is 1440.

_____________________________________________________________

A Brief Description of the output process of TCP:

Each TCP Socket has a transmission buffer, we can change its size via setsockopt so_sndbuf, when the application calls the WRITE, the kernel copies all the data from the application memory space to the Socket transmission buffer, if space Not enough (it is possible to be more data on the application, while the Socket is sent

转载请注明原文地址:https://www.9cbs.com/read-6013.html

New Post(0)