Process-IPC Sockets (iv)

Source: Internet
Author: User
Tags connect socket function prototype message queue semaphore htons

See: Https://github.com/ZhangzheBJUT/linux/blob/master/IPC (%e5%9b%9b). MD Seven Socket 7.1. Introduction to Sockets

The IPC mechanisms discussed earlier are implemented by sharing system resources on a single computer, which can be file systems (named pipes), shared physical memory (shared memory), and message queues, which can only be used by processes running on the same machine.

The Berkeley version of the UNIX system introduces a new communication tool-socket interface (socket interface). Processes on one machine can support client/server systems distributed across the network by using sockets to communicate with processes on another machine. Processes on the same machine can also communicate directly through sockets.

Sockets are a communication mechanism whereby the development of a client/server system can be done either on a local machine or across a network. The features that Linux provides, such as print services, connecting databases, and providing Web pages, and network tools such as rlogin for remote logins and FTP for file transfers, are usually communicated through sockets.

The working procedure for sockets is as follows:
For the service side,

    1. The server process uses the system to call the socket to create a socket, It is a resource of a similar file descriptor that the system assigns to the server process and cannot be shared with other processes.
    2. The server process uses system invoke bind to name the socket. The name of the local socket is the file name in the Linux file system and is typically placed in the/TMP or/usr/tmp directory. For a network socket, its name is the service identifier (port number or access point) that is related to the specific network to which the client is connected. This identifier allows Linux to go to the correct server process for a connection to a specific port number. For example, a Web server typically creates a socket on port 80, which is an identifier specifically for this purpose. The Web client (for example, the browser) knows that the site for the web that the user wants to access should use the port number 80来 to establish an HTTP connection.
    3. The server process uses system call listen to create a queue and use it to hold incoming connections from customers. At this point, the server begins to wait for the client to connect.
    4. The server process uses the system call accept the connection of the client. When you call accept, it creates a new socket that is different from the original named socket. This new socket is used only to communicate with this particular client, while the named socket is retained to continue processing connections from other customers.

For the client,

    1. The client that is based on the socket system is simpler, and the customer first calls the socket to create an unnamed socket.
    2. The server's named socket is then used as an address to call connect to establish a connection to the service side.
    3. Once the connection is established, it is possible to implement bidirectional data communication using sockets like the underlying file descriptor.
    4. Both sides call close to close the connection after use is complete
7.2 Socket Correlation function

function prototype:

 #include <sys/types.h> #include <sys/socket.h>int socket (int domain,int Type,int protocol); int bind (int socke,const struct sockaddr *address,size_t address_len); int listen (int socket,int (int socket,0 struct sockaddr *address,size_t address_len); int connetc (int socket,const struct SOCKADDR *address,size_t address_len); int close (int socket)  

function Description:

Socket function: Creates a socket that creates a socket and returns a descriptor that can be used to access the socket.                 Sockets are determined by three properties: domain (Protocol Family Protocol family), type, and protocol. Domain: Specifies the network media used in socket communication, the most common socket being af_inet and Af_unix, which refers to an Internet network. Af_unix is the use of UNIX or Linux file systems to implement local sockets, the domain of the underlying protocol is the file input \ output, and its address is the file name.                Other domains include: Af_iso and Af_xns.                                Type: Divided into stream sockets and packet sockets Flow sockets (SOCK_STREAM): Provides a reliable, ordered, bidirectional byte stream of connections. Datagram Sockets (SOCK_DGRAM): unordered, unreliable, but fast, datagram-based services.            Servers typically do not retain connection information, so they can stop and restart without disturbing their customers. Protocol (Protocol): the underlying transport mechanism allows more than one protocol to provide the required socket type, and a specific protocol can be selected for the socket.         The bind function: A named socket assigns an address in a parameter to an unnamed socket associated with a file descriptor, and the address structure length is specified by the parameter Address_len.         Naming is the path name associated to a file system for a Af_unix domain socket, which is associated to an IP port number for a af_inet domain socket.         The port number is used to identify the service, and the port number assigned by the well-known service is the same on both Linux and Unix machines, usually less than 1024. A socket address is a member of a socket field, and each socket field has its own address format, and for Af_unix sockets, its address is described by the struct sockaddr_un, which is defined in the header file sys/un.h: struct sockaddr_un{sa_family_t sum_family;                 Char sunpath[]; Af_inet is specified by sockaddr_in, including socket field, IP address, and port number struct sockaddr_in{short int Sin_fami  Ly    af_inet unsigned short int;        Prot number struct in_addr;                Internet address} struct IN_ADDR {unsigned long int s_addr;         The length and format of the address depends on the address group, and bind needs to convert a specific address structure pointer to a generic address type (struct sockaddr*).  When the function call succeeds, 0 is returned, and 1 is returned on failure.             Listen function: Create socket queue Create socket cache queue to set number of incoming connections waiting to be processed the number of incoming connections waiting to be processed cannot exceed this number, and subsequent connections will be rejected, causing the client's connection request to fail. The function call returns 0 when it succeeds, and 1 if it fails.             connetc function: Request connection parameter The socket specified by the socket is connected to the server socket specified in the parameter address, and the length of the structure to which address points is specified by the parameter Address_len.             Note: The socket specified by the parameter socket must be a valid file descriptor obtained through the socket call.              Return 0 on success, failure returns-1, possible error code: EBADF file Descriptor is invalid    Ealready the socket has an in-progress connection Etimedout connection timed out econnrefused The connection request was rejected by the server accept function: Accepting a connection creates a new socket to communicate with the client and returns the descriptor for the new socket.             The type of the new socket is the same as the server listener socket type. The address of the connecting customer is placed in the SOCKADDR structure specified by the address parameter, and if you do not care about the customer's address, you can set the addresses parameter pointer to null. The parameter Address_len specifies the length of the customer structure, and if the customer address is longer than this value, it will be truncated. Before calling accept, the Address_len must be set to the expected address length.             When this call returns, Address_len will be set to the actual length of the connection client address structure. If there are no unhandled connection requests in the queue, accept blocks until a client requests a connection.             This behavior can be changed, for example with an int flag = FCNTL (socket, F_GETFL, o_nonblock); The FCNTL function sets the flags of the socket descriptor to o_nonblock, so when there is no unhandled connection in the queue, accept does not block, but returns-1, and errno is Ewouldblock, if the accept is signaled, errno is set to E INTR.        You can use the FCNTL function to set the flag of a socket descriptor back to 0. Close function: Closing a socket is used to terminate a socket connection on the server and the client as if the underlying file descriptor were closed.
7.3 Usage Examples
Af_unix type sockets client1.c#include <sys/types.h> #include <sys/socket.h> #include <sys/un.h> #include    <unistd.h> #include <stdlib.h> #include <stdio.h>int main () {int sockfd;    int Len;    struct Sockaddr_un address;    int result;    char ch = ' A ';    Create Socket SOCKFD = socket (af_unix,sock_stream,0);    address.sun_family = Af_unix;    strcpy (Address.sun_path, "Server_socket");    Len = sizeof (address);    Connect socket result = Connect (SOCKFD, (struct sockaddr*) &address,len);     if (result==-1) {perror ("oops:client");    Exit (1);    } write (sockfd,&ch,1);    Read (sockfd,&ch,1);    printf ("char from server =%c\n", ch);    Close (SOCKFD); Exit (0);} Server1.c#include <sys/types.h> #include <sys/socket.h> #include <stdio.h> #include <sys/un.h    > #include <unistd.h> #include <stdlib.h>int main () {int server_sockfd,client_sockfd;    int Server_len,client_len; struct Sockaddr_un Server_address    struct Sockaddr_un client_address;    Unlink ("Server_socket");    Create Socket SERVER_SOCKFD = socket (af_unix,sock_stream,0);    server_address.sun_family = Af_unix;    strcpy (Server_address.sun_path, "Server_socket");    Server_len = sizeof (server_address);    Named socket bind (SERVER_SOCKFD, (struct sockaddr*) &server_address,server_len);    Create socket Queue Listen (server_sockfd,5);       Accept the connection while (1) {char ch;       printf ("Server waiting\n");       Client_len = sizeof (client_address);       Client_sockfd=accept (SERVER_SOCKFD, (struct sockaddr*) &client_address,&client_len);       Read (client_sockfd,&ch,1);       printf ("Get Data from server:%c\n", ch);       ch++;       Write (client_sockfd,&ch,1);     Close socket Close (CLIENT_SOCKFD); }}af_net type sockets client3.c#include <sys/types.h> #include <sys/socket.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <netinet/in.h> #include <arpa/inet.h>int mAin () {int sockfd;    int Len;    struct SOCKADDR_IN address;    int result;    Char ch= ' A ';    SOCKFD = socket (af_inet,sock_stream,0);    address.sin_family = af_inet;    ADDRESS.SIN_ADDR.S_ADDR = inet_addr ("127.0.0.1");    Address.sin_port = htons (9734);//9734;     Len = sizeof (address);    Connect socket result = Connect (SOCKFD, (struct sockaddr*) &address,len);     if (result==-1) {perror ("oops:client");    Exit (1);    } write (sockfd,&ch,1);    Read (sockfd,&ch,1);    printf ("char from server =%c\n", ch);    Close (SOCKFD); Exit (0);} Server3.c#include <sys/types.h> #include <sys/socket.h> #include <unistd.h> #include <stdlib.h > #include <stdio.h> #include <netinet/in.h> #include <arpa/inet.h>int main () {int SERVER_SOCKFD,    CLIENT_SOCKFD;    int Server_len,client_len;    struct sockaddr_in server_address;    struct sockaddr_in client_address;    SERVER_SOCKFD = socket (af_inet,sock_stream,0); server_address.sin_family=Af_inet;    SERVER_ADDRESS.SIN_ADDR.S_ADDR = htonl (Inaddr_any);//inet_addr ("127.0.0.1");    Server_address.sin_port = htons (9734);//9734;    Server_len = sizeof (server_address);    Bind (SERVER_SOCKFD, (struct sockaddr*) &server_address,server_len);    Create socket Queue Listen (server_sockfd,5);       Accept the connection while (1) {char ch;       printf ("Server waiting\n");       Client_len = sizeof (client_address);       Client_sockfd=accept (SERVER_SOCKFD, (struct sockaddr*) &client_address,&client_len);       Read (client_sockfd,&ch,1);       printf ("Get Data from server:%c\n", ch);       ch++;       Write (client_sockfd,&ch,1);     Close socket Close (CLIENT_SOCKFD); }}

Use the netstat command to view network connection status.
The above command is used to show that the client/server is waiting to close.

    • proto is the abbreviation for Protocol, which can be TCP or UDP.
    • recv-q and Send-q refer to the Receive queue and the send queue, which generally should be 0, if not, which means that the package is accumulating in the queue.
    • local address refers to the IP and port number of this machine.
    • foreign address refers to the host name and service to which you want to connect.
    • state refers to the state of the current connection. The three common TCP statuses are as follows:
      • listen wait for receive connection;
      • established a connection in an active state;
      • time_wait a just-terminated connection. It lasts only 1-2 minutes, and then it becomes a listen state. Because UDP is stateless, its state bar is always blank.

In addition

netstat -a 显示所有的服务,列出所有端口 (包括监听与非监听端口),显示结果可能会有数百行netstat --inet -a  显示结果将只有网络连接,包括所有正处在"LISTEN"状态和"ESTABLISHED"状态的连接    netstat -n 查看端口的网络连接情况,常用netstat -an    netstat -v 查看正在进行的工作    

Note: Host byte order and network byte order (big-endian mode): port numbers and addresses passed through sockets are binary numbers, and different computers use different byte-orders to represent integers. If the host word order and network word order are the same on your computer, you will not see any differences. To enable different types of computers to agree on the values of multibyte integers that can be transmitted over the network, you need to define network bytes. Both the client and the service side must convert their internal integer representations to network byte order before they have to be transferred.

7.4 Summary

The above is just the most basic model of network communication, in order to improve the concurrency efficiency, we will use the network model of Select, poll, Epoll and so on.

Eight IPC Summary
  • Pipe: The pipe is a half-duplex communication mode, the data can only flow in one direction, and can only be used between the processes that have affinity, process affinity usually refers to the parent-child process relationship. Famous pipe (FIFO or named pipe): A well-known pipe is also a half-duplex mode of communication, but it allows communication between unrelated processes.
  • Semaphore (Semophore): Semaphore is a counter that can be used to control access to shared resources by multiple processes. It is often used as a locking mechanism to prevent a process from accessing the shared resource while other processes are accessing the resource. Therefore, it is primarily used as a means of synchronization between processes and between different threads within the same process.
  • Signal (sinal): A signal is a more complex form of communication that notifies the receiving process that an event has occurred.
  • Shared memory: Shared memory is the mapping of memory that can be accessed by other processes, which is created by a process, but can be accessed by multiple processes. Shared memory is the fastest IPC approach and is specifically designed for low-efficiency operation of other interprocess communication modes. It is often used with other communication mechanisms, such as semaphores, to achieve synchronization and communication between processes.
  • Message Queuing: Message Queuing is a linked list of messages, stored in the kernel and identified by message queue identifiers. Message Queuing overcomes the disadvantages of less signal transmission information, only unformatted byte stream, and limited buffer size. However, the use of Message Queuing and pipelines is limited by the system (including the number of creation, the length of the message being passed, and so on).
  • Sockets: Sockets are also an inter-process communication mechanism, unlike other communication mechanisms, which can be used for process communication between different machines.

Process-IPC Sockets (iv)

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.