Https://www.ibm.com/developerworks/cn/linux/l-ipc/part6/ from
Introduction:The previous sections of this topic, such as message queues, signal lights, and shared memory, are all discussed based on the Sys v IPC Mechanism, their applications are limited to inter-process communication within a single computer. Based on the BSD interface, the inter-process communication between different computer processes can be realized. This article will mainly introduce the BSD socket interface (sockets) and an important and basic API Based on the socket interface.
Label of this article:Linux, Linux Process, code library, set interface, inter-Environment process Communication
A set of interfaces can be seen as the endpoints of inter-process communication. Each set of interface names is unique (the unique meaning is self-evident ), other processes can discover, connect, and communicate with them. The communication domain is used to describe the communication protocol of the Set interface. Different communication domains have different communication protocols and the address structure of the set interface. Therefore, when you create a set interface, specifies the communication domain. UNIX domain interface (using the interface mechanism to implement inter-process communication in a single machine) and Internet communication domain are common.
1. Background Knowledge
Linux's current network KernelCodeIt is mainly based on Berkeley's bsd unix implementation. The entire structure adopts an object-oriented layering mechanism. There are strict interface definitions between layers. Here we reference a chart in [1] to describe some communication protocols supported by Linux:
Here we only care about IPs, the Internet protocol family, which is usually referred to as the TCP/IP network. Here, we assume that the reader has some background knowledge about the network, such as understanding the layered structure of the network, which is usually referred to as the layer-7 structure, and some basic knowledge about IP addresses and routes.
Currently, Linux Network APIs are based on BSD interfaces (System V provides user interfaces based on the stream I/O subsystem, but the Linux kernel currently does not support stream I/O subsystems ). A set of interfaces is a very important concept in network programming. Linux implements a set of interfaces in the form of files, and the files corresponding to the set of interfaces belong to the special file system of sockfs, creating a set of interfaces is to create a special file in sockfs and establish a data structure to implement the set of interface functions. In other words, for each newly created BSD interface, the Linux kernel will create a new inode in the sockfs special file system. The data structure of the description set interface is socket, which will be provided later.
2. Important Data Structure
The following are several important data structures in network programming. You can go back and learn about them later in the programming API section.
(1) represents the data structure of the set interface struct socket
The Set interface is represented by the socket data structure in the following format:
Struct socket {socket_state state;/* indicates the connection status of the set of interfaces. The connection status of a set of interfaces can be idle, no corresponding port or address is bound, no connection is available, connection is in progress, connection is established, and connection is being released. */Unsigned long flags; struct proto_ops OPS;/* indicates various operations that can be performed on the set of interfaces */struct inode; /* point to the corresponding inode in the sockfs File System */struct fasync_struct * fasync_list;/* asynchronous wake up list */struct file * file; /* point to the corresponding file in the sockfs File System */struct sock SK;/* any protocol family has its specific set of interface features, this domain points to the set interface object of a specific protocol family. */Wait_queue_head_t wait; short type; unsigned char passcred ;}; |
(2) describe the data structure of the universal address of the Set interface, struct sockaddr
Due to history, in BIND, connect, and other system calls, the protocol-specific set of interface address structure pointers must be forcibly converted to the universal set of interface address structure pointers. The structure is as follows:
Struct sockaddr {sa_family_tsa_family;/* address family, af_xxx */charsa_data [14];/* 14 bytes of Protocol address */}; |
(3) The data structure struct sockaddr_in that describes the Internet address structure (this is limited to ip4 ):
Struct sockaddr_in {_ sockaddr_common (SIN _);/* Description Protocol family */in_port_t sin_port;/* Port Number */struct in_addr sin_addr; /* Internet address * // * pad to size of 'struct sockadd '. */unsigned char sin_zero [sizeof (struct sockaddr)-_ sockaddr_common_size-sizeof (in_port_t)-sizeof (struct in_addr)];}; |
In general, the reader is most concerned with the first three domains, namely the communication protocol, port number and address.
3. Several important steps of interface programming:
(1) create a set of interfaces, implemented by the system calling socket:
Int socket (INT domain, int type, int ptotocol ); |
The parameter domain indicates the communication domain, such as pf_unix (UNIX domain), pf_inet (IPv4), and pf_inet6 (IPv6). The type indicates the communication type, such as sock_stream (connection oriented) and sock_dgram (non-connection-oriented. In general, the Protocol parameter can be set to 0 unless it is used on the original set interface (the original set interface has some special functions, which will be introduced later ).
Note:Socket () is called as a set of interfaces. It allocates a new file and dentry object in the sockfs file system and associates them with the calling process through the file descriptor. A process can access the corresponding files of the interface in sockfs just like accessing an opened file. But the process must never call open () to access the file (the sockfs file system does not have a visual Installation Point, and the files in it will never appear in the system directory tree). When the set of interfaces is disabled, the kernel automatically deletes inodes from sockfs.
(2) binding address
Depending on the transport layer protocol (TCP and UDP), the processing methods of the client and server are also very different. However, no matter what transmission protocol is used by both parties, a mechanism is required to identify itself.
The communication parties are generally identified by the address and port number (generally, an IP address and a port number are often called a set of interfaces ). A specific port number represents a process that provides specific services.
For TCP transmission, both parties need to bind a set of interfaces that uniquely identify themselves to establish a connection. For UDP transmission, you only need to bind the server with a set of APIs that identify you. You do not need to bind the APIs. (for example, when you call connect, [NOTE 1]. the kernel will automatically assign a local address and local port number ). BIND () is called by the system:
Int BIND (INT sockfd, const struct sockaddr * my_addr, socklen_t my_addr_len) |
The second parameter is actually required to fill in the structure of struct sockaddr_in for IPv4, which has been described earlier. Here, we only want to emphasize the first domain of the structure. It indicates the communication protocol used by this interface, such as af_inet. Contact the first parameter called by the socket system. The reader may think about the difference between pf_inet and af_inet? In fact, the original idea is that each communication domain (such as pf_inet) may correspond to multiple protocols (such as af_inet). In fact, communication domains that support multiple protocols have not been implemented. Therefore, in the Linux kernel, AF _ *** and PF _ *** are defined as the same constant. Therefore, they can be used in different regions during programming.
Note 1:Connect () calls are also used when non-connection-oriented communication is adopted. However, there is a fundamental difference between connect () calls and connection-oriented connections: in non-connection-oriented communication, the Connect call only sets the address of the other party. The kernel writes down the address of the other party for the Local interface, and then uses send () to send data, this avoids providing the same destination address for each sending. The CONNECT () call does not involve the handshake process. In connection-oriented communication, connect () must complete a strict handshake process.
(3) request to establish a connection (initiated by a tcp client)
For communication using connection-oriented transmission protocol TCP, a more important step is to establish a connection between the communication parties (if UDP transmission protocol is used, it is not required), the system calls connect () completed:
Int connect (INT sockfd, const struct sockaddr * servaddr, socklen_t addrlen) |
The first parameter is the descriptor returned after a local SOCKET call, and the second parameter is the server address structure pointer. Connect () requests a connection from a specified set of interfaces.
Note:In contrast to connect (), on the server side, the listen () is called by the system to specify the server interface as the listener interface, and listen to each connection request sent to the server interface, and establish a connection through the handshake mechanism. The kernel maintains two queues for listen (): Completed and unfinished.
(4) accept connection requests (initiated by the TCP server)
The server creates two queues for all connection requests through the listener set interface: The completed connection queue and the unfinished connection queue (each listener set interface corresponds to these two queues, of course, generally, the server has only one listening interface ). By using accept (), the server returns the description of the set of interfaces used to represent the current connection in the connection queue header of the listener set interface.
Int accept (INT sockfd, struct sockaddr * cliaddr, socklen_t * addrlen) |
The first parameter specifies the listener interface, which is generally specified by the listen () System Call (because each listener interface corresponds to two queues that have been connected and are not connected, therefore, its internal mechanism is to use sockfd to specify which connection queue header to return a connection for the current customer. If the corresponding connected queue is empty, accept enters the sleep state ). The second parameter specifies the customer's address structure. If you are not interested in the customer's identity, you can specify it as null.
Note:For servers and clients that use TCP transmission protocol for communication, a connection must be established through the customer's request. The server accepts the connection request; this step is not required for both parties that use UDP transmission protocol.
(5) Communication
The client can receive data transmitted by the server through the set interface, or send data to the server through the set interface. All the preparations (create a set of interfaces, bindings, and other operations) are prepared for this step.
common calls to receive data from the socket: Recv, recvfrom, recvmsg, and so on. Common calls to send data to the socket include send, sendto, and sendmsg.
Int Recv (int s, void *Buf, Size_tLen, IntFlags) Int recvfrom (int s, void *Buf, Size_tLen, IntFlags, Struct sockaddr *From, Socklen_t *Fromlen) Int recvmsg (int s, struct msghdr *MSG, IntFlags) Int send (int s, const void *MSG, Size_tLen, IntFlags) Int sendto (int s, const void *MSG, Size_tLen, IntFlagsConst struct sockaddr *To, Socklen_tTolen) Int sendmsg (int s, const struct msghdr *MSG, IntFlags) |
Here we will not describe these calls in detail. I just want to emphasize that recvfrom () and recvmsg () can be used for connection-oriented and non-connection-oriented interfaces; recv () is generally used for connection-oriented interfaces. In addition, after connect () is called, send () instead of sendto () should be called, because after connect is called, the target is determined.
As mentioned above, the socket () system calls the return interface description, which is actually a file descriptor. Therefore, you can perform common read/write operations on the set of interfaces, that is, using the read () and write () methods. In practical applications, because connection-oriented communication (using TCP transmission protocol) is reliable and the original sequence of byte streams is ensured, the Read and Write methods are more suitable. Connection-oriented communication (using UDP transmission protocol) is not reliable, and byte streams do not necessarily maintain the original sequence. Therefore, the Read and Write methods are not recommended.
(6) The last step of communication is to disable the set of interfaces.
Close () is used to complete this function. Its unique parameter is the set interface description, which is not described in detail.
4. Typical call code:
Clients and servers based on the set interface can be found everywhereProgramThe complete sample code is not provided here, but their typical Call code is provided and briefly described.
(1) typical TCP server code:
... ...int listen_fd, connect_fd; struct sockaddr_in serv_addr, client_addr ;...... listen_fd = socket (pf_inet, sock_stream, 0);/* create an Internet IPv4 domain (specified by pf_inet) for connection (specified by sock_stream, if you create a non-connection-oriented interface, specify it as sock_dgram. The third parameter 0 indicates that the default transmission protocol is determined by the kernel. In this example, because a reliable connection-oriented stream-based interface is created, the kernel selects TCP as the transmission protocol for this interface) */bzero (& serv_addr, sizeof (serv_addr); serv_addr.sin_family = af_inet; /* specify the communication protocol family */serv_addr.sin_port = htons (49152);/* assign the port number */inet_pton (af_inet, "192.168.0.11", & serv_addr.sin_sddr);/* assign the address, converts an IPv4 address in dotted-decimal format to a 32-bit binary IPv4 address. */BIND (listen_fd, (struct sockaddr *) serv_addr, sizeof (struct sockaddr_in);/* bind operation */Listen (listen_fd, max_num ); /* the set of interfaces enters the listening state. max_num specifies the maximum number of connections that the kernel queues for this set of interfaces */(;;){...... connect_fd = accept (listen_fd, (struct sockaddr *) client_addr, & Len);/* Get the connection FD. */...... /* send and receive data */} |
Note:There are some common rules for assigning port numbers. Different port numbers correspond to different services or processes. For example, port 21 is usually allocated to the TCP/IP of the FTP server. Generally, the port number is divided into three segments: 0-1023 (restricted, well-known port, managed by IANA, the authority that assigns a value), 1024-49151 (the port that can be applied for registration from IANA ), 49152-65535 (temporary port, which is why the port number in the Code is 49152 ).
There are two storage methods for multi-byte integers in the memory: one is the low byte before, the high byte after, such a storage order is called low-end byte order (little-Endian ); the storage sequence of high bytes is called Big-Endian ). When processing multi-byte integers, the network protocol adopts high-end byte order, while different hosts may adopt different byte order. Therefore, you must consider the mutual conversion between the host's byte sequence and the network's byte sequence during programming. This is why the htons function is used in the program. It returns an integer in the byte sequence of the network.
(2) typical tcp client code:
... ...Int socket_fd; struct sockaddr_in serv_addr ;...... socket_fd = socket (pf_inet, sock_stream, 0); bzero (& serv_addr, sizeof (serv_addr); serv_addr.sin_family = af_inet; /* specify the communication protocol family */serv_addr.sin_port = htons (49152);/* assign the port number */inet_pton (af_inet, "192.168.0.11", & serv_addr.sin_sddr);/* assign the address, converts an IPv4 address in dotted-decimal format to a 32-bit binary IPv4 address. */Connect (socket_fd, (struct sockaddr *) serv_addr, sizeof (serv_addr);/* initiate a connection request to the server */...... /* send and receive data */...... |
Comparing the two sections of code, we can see that many calls are unique to servers or clients. In addition, for non-connection-oriented transmission protocols, the code is simpler, and the request and receiving parts are not connected.
5. Other important concepts in Network Programming
The following lists other important concepts in network programming, which are basically the functions that can be implemented by these concepts. If you need these functions during programming, you can refer to the related concepts.
(1) concept of I/O Reuse
I/O multiplexing provides a capability that enables a process to obtain this information in a timely manner when an I/O condition is met. I/O multiplexing is generally used when a process needs to process multiple descriptive words. One of its advantages is that the process is not blocked on real I/O calls, but on select () calls. Select () can process multiple descriptive words at the same time, if I/O of all the descriptive words it processes are not in the ready state, it will be blocked; if one or more descriptive words I/O are in the ready state, select () is not blocked, and corresponding I/O operations are performed based on the prepared specific description.
(2) UNIX communication domain
The above section mainly describes the pf_inet communication domain to implement inter-process communication between the Internet. A set of Interfaces Based on UNIX communication domains (pf_local is the communication domain specified when a socket is called) can implement inter-process communication between a single machine. The UNIX communication domain interface has several advantages: the Unix communication domain interface is usually twice the speed of the TCP interface; another advantage is that, description can be transferred between processes through the Unix communication domain interface. All objects that can be described by descriptive words, such as files, pipelines, famous pipelines, and APIs. After we obtain the descriptive word of this object in some way, you can use a set of Interfaces Based on the Unix domain to transmit the description. The description value received by the receiving process is not necessarily the same as that passed by the sending process (the description is specific to the process), but points to the same item in the kernel file table.
(3) original set of interfaces
The original set interface provides functions not provided by the general set interface:
- The original interface can read and write some control protocol groups for control, such as ICMPv4, to implement some special functions.
- The original interface can read and write special IPv4 packets. Generally, the kernel only processes data packets with specific protocol fields. Therefore, some data packets with different protocol fields need to be read and written through the original interface;
- It is also interesting to use the original interface to construct an IPv4 header.
Root permission is required to create the original set of interfaces.
(4) access to the data link layer
Access to the data link layer allows users to listen to all groups on the local cable without using any special hardware devices, to read data link layer groups in Linux, you must create an interface of the sock_packet type and have the root permission.
(5) out-of-band data)
If you want to send important information immediately through a set of APIS (without queuing), refer to the documents related to out-of-band data.
(6) Multicast
The Linux kernel supports multicasting, but by default, most Linux systems disable multicasting. Therefore, to implement multicast, you may need to reconfigure and compile the kernel. For details, refer to [4] and [2].
Conclusion:The content of programming on Linux sets of interfaces can be said to be extremely rich. At the same time, it involves a lot of network background knowledge. Interested readers can find a more systematic and comprehensive introduction in [2.
So far, this topic series (Linux environment inter-process communication) are all over. In fact, the general meaning of inter-process communication usually refers to message queues, signal lights and shared memory, which can be POSIX or sys v. This series also introduces pipelines, famous pipelines, signals, and interfaces. It is a more general inter-process communication mechanism.
References
- Understanding the Linux kernel, 2nd edition, by Daniel P. bovet, Marco cesati, focuses on each topic and has a clear context. Network Analysis is concentrated on the data connection layer, network layer, and transmission layer of the TCP/IP protocol stack.
- UNIX Network Programming Volume 1: Set of interface APIs and X/Open Transmission API, Author: W. Richard Steven S, Translator: Yang jizhang, Tsinghua University Press. It not only provides an excellent description of network programming of sets of interfaces, but also elaborates on the relevant network background knowledge in great detail. Both entry-level and in-depth research are rare materials.
- Linux KernelSource codeScenario Analysis (II), Mao decao, Hu Ximing, and Zhejiang University Press provide kernel code analysis for the UNIX domain interface.
- The GNU/Linux programming guide is intended for beginners, applications, masters, second edition, and Kurt wall.
About the author
Zheng yanxing, male, is now pursuing a doctorate degree in network direction from the computer College of the National Defense University. You can contact him by email mlinux@163.com.