[Linux C Programming] Network Communication

tags: The internet  application  data  linux  Embedded

Telecommunication

1. Briefly describe OSI's seven-layer protocol model and TCP/IP's four-layer protocol model

OSI seven-layer model: application layer, presentation layer, session layer, transport layer, network layer, data link layer, physical layer

TCP/IP (Linux) four-layer model: application layer, transport layer, network layer, network interface layer

 

2. Briefly describe the role of each layer of TCP/IP

(1) Network Interface Layer: The network interface layer is the bottom layer of the TCP/IP protocol software, which is responsible for converting binary streams into data frames and sending and receiving data frames. Data frame is the basic unit of network transmission

(2) Internet Layer The network layer is responsible for selecting the transmission path of the datagram in the communication between hosts, that is, routing. When the network layer receives a request from the transport layer, it transmits a packet with destination address information. This layer encapsulates the packet in an IP datagram, fills in the header of the datagram, uses a routing algorithm to determine whether to deliver the datagram directly or pass it to the router, and then delivers the datagram to the appropriate network interface for transmission.

The network layer is also responsible for processing incoming datagrams, checking their validity, and using routing algorithms to determine whether the datagrams should be processed locally or forwarded.

If the destination machine of the datagram is in the network where the machine is located, this layer software will remove the header of the datagram, and then select the appropriate transport layer protocol to process the packet. Finally, the network layer also needs to send and receive ICMP (Internet Control Message Protocol) error and control messages.

(3) Transport Layer (Transport Layer) The transport layer is responsible for providing communication services between applications. This kind of communication is also called end-to-end communication. The transport layer must systematically manage the flow of information and provide reliable transmission services to ensure that data arrives without errors and disorder. In order to achieve this goal, the transport layer protocol software must negotiate, let the receiver send back confirmation information and let the sender retransmit the lost packets. The transport layer protocol software divides the data stream to be transmitted into packets, and hands each packet together with the destination address to the network layer to send.

(4) Application Layer The application layer is the highest layer of the hierarchical model. In this highest layer, users call applications to access feasible services through the TCP/IP Internet. The application program that interacts with each transport layer protocol is responsible for receiving and sending data. Each application selects the appropriate transmission service type, and encapsulates the data for transmission to the lower layer according to the format requirements of the transmission layer.

3. Protocols of each layer of TCP/IP


The first part is called the network layer. Mainly include Internet Protocol (IP), Internet Control Message Protocol (ICMP) and Address Resolution Protocol (ARP)

Internet Protocol (IP)

The protocol is designed to interconnect packet-switched communication networks to form an internet communication environment. It is responsible for transmitting data blocks called data packets from its higher-level software between the source host and the destination host, and it provides a connectionless delivery service between the source and destination

Internet Control Message Protocol (ICMP)

It is not actually part of the IP layer, but it works directly with the IP layer to report certain errors on the network. Allow Internet routers to transmit error messages or test packets.

Address Resolution Protocol (ARP)

ARP is actually not part of the network layer, it is located between the IP and data link layers, it is a protocol that performs translation between a 32-bit IP address and a 48-bit physical address

The second part is the transport layer protocol, including transmission control protocol and user data message protocol

Transmission Control Protocol (TCP):

This protocol is responsible for establishing a dialogue between user processes on the network. It ensures reliable communication between processes. The functions provided are as follows:

1. Monitor the input dialog establishment request

2. Ask another web site to talk

3. Send and receive data reliably

4. Close the conversation moderately

TCP is an important transport layer protocol whose purpose is to allow reliable data exchange with other nodes on the network. It can provide port number decoding to identify the application program of the host, and complete the reliable transmission of data. The TCP protocol has a strict built-in error checking algorithm to ensure the integrity of the data. TCP is a byte-oriented sequential protocol, which means that the packet Each byte of is assigned a sequence number, and each packet is assigned a sequence number

 

User Datagram Protocol (UDP):

UDP provides an unreliable connectionless transport layer service, which allows data to be transferred between the source and destination without having to establish a dialogue before transferring the data. It is mainly used for non-connected applications, such as: video on demand

UDP is also a transport layer protocol. It is a connectionless and unreliable transmission service. When receiving data, it does not provide confirmation information to the sender. It does not provide the order of input packets. If a packet is lost or duplicated, It will not send error messages to the sender. Because it has lower overhead when performing functions, the execution speed is faster than TCP

 

4. Please briefly describe the TCP/IP three-way handshake process

The first step (A->B): Host A sends a TCP message containing the SYN (Synchronize) flag to host B. The SYN synchronization message will specify the port used by the client and the initial sequence number of the TCP connection;

Step 2 (B->A): After host B receives the SYN message from the client, it will return a SYN+ACK message, indicating that the request of host B is accepted, and the TCP sequence number is increased by one, and ACK is confirmed (Acknowledgement).

The third step (A->B): Host A also returns an acknowledgement message ACK to the server. Similarly, the TCP sequence number is increased by one, and the TCP connection is completed.

5. How to choose TCP and UDP?

The choice of the protocol should take into account the reliability of the data, the real-time nature of the application and the reliability of the network.

·Applications that require high data reliability need to choose the TCP protocol, and applications that require less data reliability are optional

Choose UDP transmission.

·The three-way handshake and retransmission confirmation in the TCP protocol can ensure the reliability of data transmission, but the use of the TCP protocol will

There is a large time delay, so it is not suitable for applications that require high real-time performance; while the UDP protocol has good real-time performance.

·If the network condition is not very good, you need to use the TCP protocol (such as in the case of a wide area network), and the network condition is very good

Selecting UDP protocol can reduce network load.

6. TCP, UDP programming model

 


 

7.Linux TCP network programming function

socket: create a socket socket

bind: Bind the IP address and port address to the socket

connect: This function is used to connect the client to the server after binding

listen: set the maximum connection requirement that can be handled

accept: accept socket connection

send: send data

recv: receive data

 

(1)socket

The role of the function: create a new socket socket

The prototype of the function: int socket(int domain,int type,int protocol)

Function parameter: domain: indicates which address type is used AF_INET IPV4

AF_INET6 IPV6 network protocol

Type: SOCK_STREAM: TCP provides reliable, connection-oriented communication flow for data flow

SOCK_DGRAM: UDP uses discontinuous and unreliable data packets to connect

SOCK_RAM: Provide original network protocol, protocol test

Protocol: Specify the socket transmission protocol number, set it to 0

Return value: success returns the socket descriptor, failure -1

Header file: #include<sys/socket.h>

 

(2)bind

The role of the function: bind the IP address

The prototype of the function: int bind(int sockfd,struct sockaddr* my_addr,int addrlen)

The parameters of the function: sockfd: socket descriptor

My_addr: host address

        struct sockaddr

        {

         u_short sa_family;

         char sa_data[14];

        };

        struct sockaddr_in

        {

Short int sin_family; /* Internet address family */

Unsigned short int sin_port; /* port number */

Struct in_addr sin_addr; /* IP address */

Unsigned char sin_zero[8]; /* fill in 0 */

        };

Addrlen: length of the address of sockaddr

Return value: success 0 error -1

Header file: #include <sys/types.h>

     #include <sys/socket.h>

 

(3)connect

The role of the function: to establish a socket connection, usually the client connects to the server

The prototype of the function: int connect(int sockfd,struct sockaddr* serv_addr,int addrlen)

Function parameter: serv_addr: indicates the IP address of the server to be connected

Addrlen: length of struct sockaddr

Return value: success 0, error -1

 

(4)listen

The role of the function: listening to the network, waiting for connection

The prototype of the function: int listen(int sockfd, int backlog)

The parameters of the function: sockfd: socket descriptor

Backlog: the number of clients allowed to access

Note: The listener is not connected, just set the listen mode of the socket, and accept the real connection

Return value: success 0 error -1

 

(5)accept

The role of the function: receiving network connection, client connection, three-way handshake here

The prototype of the function: int send(int sockfd,struct sockaddr * addr, int * addrlen)

Function parameter: addr: connection is successful, fill in the address of the remote client

Addrlen: length of struct sockaddr

Return value: success returns new fd, failure -1

 

(6)send

The role of the function: send data through the socket, send data to the other party

The prototype of the function: int send(int sock_fd,const void *msg,int len,unsigned int flags)

Function parameter: Socket connection descriptor established by sock_fd:accept to connect to the remote IP address

Msg: sent data

Len: data length

Flags: set to 0

Return value: Success is the number of bytes actually transmitted, error -1

 

(7)recv

The role of the function: receive data through the socket

The prototype of the function: int recv(int sock_fd,void * buf, int len,unsigned flag);

The parameters of the function: sock_fd: accept socket socket descriptor

Buf: storage address

Len: Maximum length of received data

Return value: Return the number of bytes received successfully, -1 on failure

 

8. Byte order conversion function

Different types of CPUs may store variables in different byte order: some systems have high order first and low order second, while some systems have low order first and high order last. The order of data transmitted over the network must be unified. . So when the internal byte storage order is different from the network byte order, it must be converted

Network byte order adopts big-endian sorting

Header file: #include <arpa/inet.h>

Send from the host to the network (integer data):

uint32_t htonl(uint32_t hostlong); //32-bit data transmission, from the host to the network

uint16_t htons(uint16_t hostshort); ///16-bit data transmission, from host to network

From network to host:

uint32_t ntohl(uint32_t netlong); //32-bit data reception, from the network to the host

int16_t ntohs(uint16_t netshort); //16-bit data reception, from the network to the host

These function names are easy to remember, h means host, n means network, l means 32-bit long integer, and s means 16-bit short integer. For example, htonl means to convert a 32-bit long integer from the host byte order to the network byte order, for example, the IP address is converted and ready to be sent. If the host is in little-endian, these functions will convert the parameters into big-endian and then return. If the host is in big-endian, these functions will not convert and return the parameters intact.

 

9. Address format conversion

Convert decimal point format to binary format: inet_addr, inet_pton

(1)inet_addr()

The prototype of the function: unsigned long int inet_addr(const char *cp)

Return value: Returns the corresponding binary data if successful, -1 if failed

Function parameter: cp: put a dotted IP address such as "192.168.1.100"

 

(2)inet_pton()

The prototype of the function: int inet_pton(int af,const char *src,void *dest)

The parameters of the function: af:AF_INET AF_INET6

Src: the dotted IP address to be converted

Return value: Success 1, invalid format 0, error -1

(3)inet_ntop

The role of the function: Binary address is converted into decimal point form

The prototype of the function: const char * inet_ntop(int af,const void* src,socket_t size)

 

10.Linux UDP network programming function

(1)sendto

The role of the function: transmit socket data, UDP is used more

The prototype of the function: int sendto(int sockfd,void* msg,int len,unsigned int flags,const struct sockaddr * to,int tolen)

The parameters of the function: sockfd: socket descriptor

Msg: sent message memory

Len: message length

Toaddr: the destination address of the message to be sent

        tolen:sizeof(struct sockaddr)

Return value: Success: the number of bytes actually transferred, error: -1

 

(2)recvfrom

The role of the function: receive data from sockfd

The prototype of the function: int recvfrom(int sockfd,void *buf,int len,unsigned int flags,struct sockaddr * fromaddr,int * fromlen)

Return value: Success: Return the received byte length Error: -1

 

supplement:

1. The scope and application of five types of IP

IP addresses are divided into five categories. Class A is reserved for government agencies, Class B is allocated to medium-sized companies, Class C is allocated to anyone in need, Class D is used for multicast, Class E is used for experiments, and all types can be accommodated. The number of addresses is different.

Among them, the three types of addresses of class A, class B, and class C are used for TCP/IP nodes, and the other two classes of class D and E are used for special purposes.

Class A address

⑴ The first byte of class A address is the network address, and the other 3 bytes are the host address.

⑵ Class A address range: 1.0.0.1—126.155.255.254

⑶ Private address and reserved address in Class A address:

① 10.X.X.X is a private address (the so-called private address is an address that is not used on the Internet but is used in the local area network).

② 127.X.X.X is a reserved address and is used for loop testing.

Class B address

⑴ The first byte and the second byte of the class B address are the network address, and the other 2 bytes are the host address.

⑵ Class B address range: 128.0.0.1—191.255.255.254.

⑶ Private address and reserved address of Class B address

① 172.16.0.0—172.31.255.255 is a private address

② 169.254.X.X is a reserved address. If your IP address is automatically obtained, and you have not found an available DHCP server on the network. You will get one of the IPs.

Class C address

⑴ The first byte, the second byte and the third byte of the C type address are the network address, and the fourth byte is the host address. In addition, the first three bits of the first byte are fixed at 110.

⑵ C address range: 192.0.0.1—223.255.255.254.

⑶ Private address in class C address:

192.168.X.X is a private address.

Class D address

⑴ Class D address does not distinguish between network address and host address, and the first four bits of its first byte are fixed at 1110.

⑵ D address range: 224.0.0.1—239.255.255.254

Class E address

⑴ E-type address does not distinguish between network address and host address. The first five digits of its first byte are fixed at 11110.

⑵ Class E address range: 240.0.0.1—255.255.255.254

 

2. How to make UDP achieve reliable transmission

Customize the communication protocol, define some reliable protocols at the application layer, such as checking the order of packets, repeating packets, etc. If you do not receive ACK from the other party, resend the packet

UDP does not have Delievery Garuantee, and there is no guarantee of order, so if you require your data to be sent and received efficiently, but also in order, confirmation of receipt, etc., you need to build your own protocol on the UDP protocol. For example, RTCP, the RTP protocol is a protocol between the transport layer and the application layer designed specifically for IP phones on the H.323 protocol cluster on top of the UPD protocol.

 

3. Three handshake, four wave hands to describe in detail the process and function, advantages and disadvantages

(Establishing a connection agreement) the process of three-way handshake

(1) The client sends a TCP message with the SYN flag to the server, which is the message 1 in the three-way handshake process

(2) The server responds to the client. This is the second message in the three-way handshake process. This message carries both the ACK flag and the SYN flag. Represents the response to the client's SYN message just now, and at the same time marks the SYN to the client, asking whether the client is ready for data communication

(3) The client must respond to the server with an ACK message again, which is message 3.

The role of the three-way handshake

Check whether the sending and receiving capabilities of both parties are normal

Advantages of the three-way handshake:

If the connection confirmation from the client is not received, the server will not establish the connection. So as to avoid wasting server resources.

Disadvantages of the three-way handshake:

Let the attacker take advantage of the flaws in the TCP protocol to send a large number of attack messages with forged source addresses without responding to the ACK packet. The server will retry five times by default, which may cause the queue in the target server to be full and prevent it. Access by other legitimate users.

 

(Connection Termination Agreement) The process of waving four times

(1) The TCP client sends a FIN to close the data transmission from the client to the server (message segment 4)

(2) When the server receives this FIN, it sends back an ACK, confirming that the sequence number is the received sequence number plus 1 (message segment 5). Like SYN, one FIN will occupy one sequence number.

(3) The server closes the client's connection and sends a FIN to the client (message segment 6)

(4) The client sends back an ACK message confirmation, and sets the confirmation sequence number to the received sequence number plus 1 (message segment 7)

The effect of four waves

In full-duplex working mode, both parties need to close the connection

 

4. Choice of TCP and UDP

Use TCP:

When there is a requirement for the quality of network communication, such as: the entire data should be accurately and accurately transmitted to the other party. This is often used for some reliable applications, such as HTTP, HTTPS, FTP and other file transfer protocols, and POP, SMTP and other mail transmissions. Agreement.

In daily life, the common applications that use the TCP protocol are as follows:

Browser, using HTTP

FlashFXP, FTP used

Outlook, POP, SMTP used

Putty, Telnet, SSH

QQ file transfer

…………

Use UDP:

When the network communication quality is not high, the network communication speed is required to be as fast as possible, then UDP can be used.

For example, in daily life, the common applications that use the UDP protocol are as follows:

QQ Voice

QQ video

TFTP

……

Intelligent Recommendation

Linux System Programming - Network Communication

contents Create a socket 2. Binding address 3. Monitor connection 4. Accept connection 5. Running a connection 6. Turn off the channel 7. Transport data 8. Convert word sequence 9. Example Create a so...

C# programming--socket network communication

C# programming-socket network communication 1. Network socket concept: TCP/IP (Transmission Control Protocol/Internet Protocol) Transmission Control Protocol/Internet Protocol. socket means "sock...

Linux programming network programming - udp communication

The difference between TCP and UDP TCP (Transmission Control Protocol): 1. For connection, there is a process of connecting three handshakes and disconnecting four handshakes. 2. Transmit in the form ...

Introduction to C# Programming and Network Communication Programming

Introduction to C# Programming and Network Communication Programming Write a "Hello Word!" program Write a simple Form window program in C# with a text box textEdit and a send button button....

linux c network programming

The OSI seven-layer network model consists of 1 to 7 layers from bottom to top, which are: Physical layer, Data link layer, Network layer, Transport layer, Session layer, Presentation layer, Applicati...

More Recommendation

Linux C++: Network Programming

I have studied C language before, but now I can review it when I learn C++ to re-consolidate the basic knowledge. What is a socket: TCP uses the host's IP address plus the port number on the host as t...

Linux C++ network programming

Linux C++ Network Programming (2) Preface After learning Linux, C++, networking and other knowledge in a split way in the previous section, this section will combine these three modules and learn thes...

Linux C ++ Network Programming

To find a good job in Linux C ++, there is more than the interview process, then this article is customized for you. Because as a student of a school, I am experiencing the article in the process of s...

Linux network programming case: SOCKET local communication and network communication

Local process communication Effect picture: Telecommunication Effect picture...

LINUX network programming---implementing TCP simple communication

Memorize flow chart   Server code: #include<stdio.h> #include<errno.h> #include<string.h> #include<strings.h> #include<unistd.h> #include<stdlib.h> #include<...

Copyright  DMCA © 2018-2026 - All Rights Reserved - www.programmersought.com  User Notice

Top