TCP/IP details (to most)

Source: Internet
Author: User
Tags domain list

When storing some information, it does not need to occupy a full byte, but only needs to occupy a few or one binary bit. For example, when storing a switch value, there are only two States: 0 and 1. Use one binary digit. To save storage space and simplify processing, the C language also provides a data structure called "bit domain" or "bit segment ". The so-called "bit field" refers to dividing the binary character in a byte into several different regions and showing the digits of each region. Each domain has a domain name.ProgramPerform operations by domain name. In this way, several different objects can be represented by a byte binary field.

1. Definition of a bit field and description of a bit field variable the definition of a bit field is similar to that of a structure, in the form:

Struct bit domain structure name
{Bit domain list };
The format of the bit domain list is: type description Character Domain Name: Bit domain Length
For example:
Struct BS
{
Int A: 8;
Int B: 2;
Int C: 6;
};

The description of bitfield variables is the same as that of structure variables. You can first define and then describe, and define or directly describe these three methods. For example:
Struct BS
{
Int A: 8;
Int B: 2;
Int C: 6;
} Data;
Data is a BS variable. If the int type occupies 4 bytes, the data type occupies 4 bytes. Where a occupies 8 places, B occupies 2 places, and C occupies 6 places. The remaining 16-bit space is not used. The definition of bit domain is described as follows:

1. A single-byte field must be stored in the same byte, and cannot span two bytes. If the remaining space of one byte is insufficient to store another domain, it should be stored from the next unit. You can also intentionally enable a domain to start from the next unit. For example:
Struct BS
{
Unsigned A: 4
Unsigned: 0/* airspace */
Unsigned B: 4/* stored from the next unit */
Unsigned C: 4
}
In the definition of this bit field, a occupies 4 bits in the first byte, And the last 4 bits enter 0 to indicate that it is not used. B starts from the second byte and occupies 4 bits, and C occupies 4 bits.

2. Because the bit field cannot span two bytes, the length of the bit field cannot exceed the length of one byte, that is, it cannot exceed 8-bit binary.

3. A bit domain can be a non-bit domain name. In this case, it is only used for filling or adjusting the position. An anonymous domain cannot be used. For example:
Struct K
{
Int A: 1
INT: 2/* The two digits cannot be used */
Int B: 3
Int C: 2
};
From the above analysis, we can see that the bit field is essentially a structure type, but its members are allocated by binary.

2. The use of bit domains is the same as that of structure members. The form is generally: Bit domain variable name-bit domain name can be output in various formats.
Main (){
Struct BS
{
Unsigned A: 1;
Unsigned B: 3;
Unsigned C: 4;
} Bit, * pbit;
Bit. A = 1;
Bit. B = 7;
Bit. c = 15;
Printf ("% d, % d, % d \ n", bit. A, bit. B, bit. C );
Pbit = & bit;
Pbit-> A = 0;
Pbit-> B & = 3;
Pbit-> C | = 1;
Printf ("% d, % d, % d \ n", pbit-> A, pbit-> B, pbit-> C );
}
In the preceding example, the bit domain structure Bs is defined. The three bit domains are A, B, and C. This section describes the BS type variable bit and the BS type pointer variable pbit. This indicates that pointers can also be used for bit fields. The program's Lines 9, 10, and 11 assign values to the three single-digit domains. (Note that the value assignment cannot exceed the permitted range of the bit field) The program outputs the content of the three fields in integer format in line 1. Row 3 sends the bit address of the bit field variable to the pointer variable pbit. Row 14th re-assigns a value to bit field A as a pointer and assigns it to 0. Row 15th uses the compound bitwise operator "& =", which is equivalent to 7 in the original value of pbit-> B = pbit-> B & 3-bit Domain B, the bitwise AND operation result of 3 is 3 (111 & 011 = 011, And the decimal value is 3 ). Similarly, the Code uses the compound bitwise operation "| =" in line 1, which is equivalent to pbit-> C = pbit-> C | 1 and the result is 15. The program output the values of the three fields in the pointer mode in Row 3.

I will tell you the reasons for using the bits:

1. It can package data with an odd number in length to save storage space;

2. It can easily access part of an integer value.
First, I would like to remind you of the following points:

1. There are only three types of bit segments: int, unsigned int, and signed Int. (Of course, it is not up to me to determine whether the int bit segments can take negative numbers, this is determined by your compiler. Bit, bit, which is used to represent the bit length of a field. It only has an integer value and does not have the float type 7.2. If you say yes, then you acknowledge the concept of 7.2 people, and of course there is no char type );

2. A colon and an integer after the member name, which specifies the bit length (BIT) of the bit segment );

3. Many compilers limit the length of a bit segment member to an int; 4. The implementation of a bit segment member in the memory is determined by the compiler from left to right or from right to left, but both are right.
Next let's take a look at what it is (I assume that the length of the machine is 32 characters ):
Struct word
{
Unsigned int chara: 6:
Unsigned int Font: 7;
Unsigned int maxsize: 19;
};
Struct word Chone;
This section is taken from a Text Formatting software I have compiled. It can accommodate up to 64 characters (that is, the unsigned int chara: 6 Characters in total) different character values, can process 128 (both unsigned int Font: 7; both 2 to the power of 7) Different fonts, and 2 to the power of 19 characters in length. We can see that maxsize is 19 BITs and cannot be accommodated by a short int type value. We can also see that the length of the remaining Members is smaller than that of char, this reminds us of sharing the 32-bit machine font length, which avoids the use of a 32-bit integer to represent the maxsize bit segment. How is it? It should also be noted that Code It cannot be implemented on a 16-character long machine. Why? Let me remind you to see the above 3rd points, you will understand!
Did you find this thing useless? If you nod, you are wrong! How can such a great creation be useless? (You are not interested in system programming. I believe you will change this point of view )? Do you know the disk controller? The communication between the floppy disk and its controller is as follows:
│ Reject 5 → │ reject 5 → │ reject 9 → │ reject 8 → │ reject 1 → │ reject 1 → reject 1 → reject 1 → reject 1 → reject 1 → reject
The meaning of the above bit segments from left to right is: 5-bit command, 5-bit sector, 9-bit track, 8-bit error code, 1-Bit Head loaded, 1-bit write protection, 1-bit disk spinning, 1-Bit Error identifier, and 1-bit ready. How can it be implemented? First, you can write and read:
Struct disk_format
{
Unsigned int command: 5;
Unsigned sector: 5;
Unsigned track: 9;
Unsigned err_code: 8;
Unsigned ishead_loaded: 1;
Unsigned iswrit_protect: 1;
Unsigned isdisk_spinning: 1;
Unsigned iserr_ocur: 1;
Undigned isready: 1;
};
Note: In the Code, except for the first line, the unsigned int is used to declare the bit segment, which saves Int. This is feasible. For details, see the anci c standard.
If we want to access the 044c18bfh address, it will be like this:
# Define disk (struct disk_format *) 0x044c18bf)
Disk-> sector = fst_sector;
Disk-> track = fst_track;
Disk-> command = write;
Of course, those are all macro-defined!
It is very convenient for us to use bit segments to achieve this purpose. In fact, this can also be achieved through shift or blocking. You will know which one is more convenient after you try it!
Our topic today is here. If you have any questions, please email me: arhuwen@163.com;
Special statement: Do not use the above content for illegal behaviors. Otherwise, you will be responsible for the consequences. In addition, this article cannot be used for any action to seek commercial benefits!

C compiler allocates the default structure space
In the C language, the structure is a composite data type, and its components can be both variables of basic data types (such as int, long, float, and so on, it can also be a data unit of a composite data type (such as a number group, structure, union, and so on. In the structure, the compiler allocates space for each member of the structure based on its natural alignment condition. Each member is stored in an in-memory sequence in the declared order, the address of the first member is the same as the address of the entire structure. By default, the C compiler allocates space for each variable or data unit based on its natural limitations. See table 1:


Table 1: Natural bounded conditions under Win32
For example, the following structure shows the allocation of member spaces:
Struct test {
Char x1;
Short X2;
Float X3;
Char X4;
};

Figure 1: Default structure space allocation
The first member of the structure X1, whose offset address is 0, occupies 1st bytes. The second member X2 is of the short type, and its starting address must be two byte pairs. Therefore, the compiler fills a Null Byte between X2 and X1. The third member X3 and fourth member X4 of the structure exactly fall on their natural peer address, and no additional bytes are needed before them. In the test structure, the X3 member requires a 4-byte bounded boundary and is the maximum boundary unit required by all the members of the structure. Therefore, the natural boundary condition of the test structure is 4 bytes, the compiler fills in three NULL bytes after Member X4. The entire structure occupies 12 bytes of space.

Bits in the Structure
The so-called bitwise segment is a member of the struct type that defines the length in units of bits. The compiler follows the following principles for allocating the structure median:
? For a bit segment with a length of 0, the next bit segment is stored from the next storage unit:
For example:
Struct t {
Unsigned char A: 1;
Unsigned char B: 2;
Unsigned: 0;
Unsigned C: 3;
};
The members a and B of structure T are in one storage unit, while C is in another storage unit.
? A single segment must be stored in the same storage unit and cannot be stored across two units:
For example:
Struct t {
Unsigned char A: 4;
Unsigned char B: 6;
};
The member A of structure T is in one storage unit, and B is in another storage unit.

Change the default Allocation Policy of the C Compiler
Generally, you can use the following two methods to change the default peer condition:
? Use pseudoinstructions # pragma pack ([N])
? Use command line parameters during compilation
# Pragma pack ([N]) pseudoinstructions allow you to select the peer policy adopted by the compiler to allocate space for data, as shown in table 2:


Table 2: Change the default peer Condition
In microsfot visual c ++, the command line parameter/ZP [N] can change the default peer condition. In Borland C ++ builder, the command line parameter-A [n] can change the default peer condition. The meaning of N is the same as that in # pragma pack.
For example, after the # pragma pack (1) Directive is used, the space allocation of each member in the test structure is shown in Figure 2:


Figure 2: structure space allocation after # pragma pack (1)

Application Instance

In our daily programming work, especially the processing of some network transactions, we often have various protocols with others: for example, the header I sent to you in 20 bytes, the first four bytes represent ...... And so on. Many people get various information through the pointer offset method. This method is not only complicated in programming, but also troublesome to modify the program once the Protocol changes. After learning about the compiler's allocation principles for the structure space, we can use this feature to define our own protocol structure and obtain various information through access structure members. In this way, not only programming is simplified, but even if the protocol is changed, we only need to modify the definition of the protocol structure. Other programs do not need to be modified, saving time and effort. The following uses the TCP protocol header as an example to describe how to define the protocol structure.
TCP protocol header 3:

TCP Message format

 -TCP :( Transmission Control Protocol)
        Connection-oriented reliable transmission protocol for users
                   A virtual circuit is provided between applications.

-Source Port: The call end slogan
-Destination Port: the name of the called end.
-Sequence number: the serial number assigned to the message. It is used to track the message communication sequence and ensure no loss.
-Acknowledgement number: the serial number of the expected next TCP packet, which indicates
                  Confirmation of correct receipt of the packets before this sequence
-Header length (hlen): the number of bytes in the header of the message.
-Reserved: set to 0.
-Code bits: Control Function (such as TCP connection establishment and termination)
-Window: number of bytes that the sender agrees to receive
-Checksum: checksum of header and data fields
-Urgent Pointer: indicates the end of an emergency data segment.
-Option: the maximum value of the currently defined TCP segment.
-Data: Upper-layer protocol data

  The establishment of a TCP connection is actually a synchronization process (also called a three-way handshake)  
Three-way handshake:
    1: host a sends a connection request packet to host B
    2: Host B sends consent links and requests for synchronization to host a (one upon sending and one upon receiving)
    3: host a needs to send a packet to confirm synchronization of host B's requirements

UDP Message format
 -Udp: (User datemediprotocol) connectionless unreliable transmission protocol
-Source Port: The call end slogan
-Destination Port: the name of the called end.
-Header length (hlen): the number of bytes in the header of the message.
-Checksum: checksum of header and data fields
-Data: Upper-layer protocol data

UDP transmission does not provide ack reverse validation mechanism, traffic control, and message serial number control. Therefore
UDP packets may be lost, duplicated, or unordered, and the reliability of communication will be caused
Use layer protocols to provide protection. However, the UDP Message format and control mechanism are simple, so communication is enabled.
Small sales. SNMP and DNS application layer protocols are all transmitted over UDP.
.

The TCP protocol header is defined as follows:
Struct tcpheader {
Short srcport; // 16-bit source port number
Short dstport; // 16-bit destination port number
Int serialno; // 32-bit serial number
Int ackno; // 32-bit confirmation number
Unsigned char haderlen: 4; // 4-bit Header Length
Unsigned char reserved1: 4; // retain four of the six digits
Unsigned char reserved2: 2; // retain two of the six digits
Unsigned char URG: 1;
Unsigned char ack: 1;
Unsigned char PSH: 1;
Unsigned char rst: 1;
Unsigned char SYN: 1;
Unsigned char Fin: 1;
Short windowsize; // 16-bit window size
Short tcpchksum; // 16-bit TCP check
Short urgentpointer; // 16-bit emergency pointer
};
The protocol structure can also be defined as follows:
Struct tcpheader {
Short srcport; // 16-bit source port number
Short dstport; // 16-bit destination port number
Int serialno; // 32-bit serial number
Int ackno; // 32-bit confirmation number
Unsigned char haderlen: 4; // 4-bit Header Length
Unsigned char: 0; // retain four of the six digits
Unsigned char Reserved: 2; // retain 2 of the 6 digits
Unsigned char URG: 1;
Unsigned char ack: 1;
Unsigned char PSH: 1;
Unsigned char rst: 1;
Unsigned char SYN: 1;
Unsigned char Fin: 1;
Short windowsize; // 16-bit window size
Short tcpchksum; // 16-bit TCP check
Short urgentpointer; // 16-bit emergency pointer

};

From http://hi.baidu.com/luckymouse2009/blog/item/e08f5d4e912b993eaec3abb5.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.