C + + Socket

Source: Internet
Author: User
Tags file transfer protocol

1. IP Address: The network address assigned to the local host according to the TCP/IP protocol. Just like two processes to communicate, any process should know the location of the communication.

2, port number: Used to identify the process of local communication, convenient for the OS to submit data. The process specifies the network IP of the other process, but this IP is only used to identify the host on which the process resides, how can it find the process running on that host? Port number.

3. Connection: Two communication links between processes.

4, semi-related: In the network with a ternary group can be globally unique flag a process. (Protocol, local address, local port number). Such a ternary group is called a semi-correlation. It specifies each part of the connection.

5, full-Related: A complete inter-network process communication needs to consist of two processes, and can only use a high-level protocol. It is not possible to present a process for the TCP protocol, another process for the UDP protocol. A five-tuple identification is required for complete inter-network communication. (Protocol, local address, local port number, remote address, remote port number).

6.

Client/server mode communication process is the active request mode: First the server to start first, and according to the request to provide the appropriate services: 1. Opens a communication channel and informs the local host that it is willing to receive customer requests at a recognized address (such as FTP 21); 2. Wait for a customer request to reach the port; 3. Receives a duplicate service request, processes the request, and sends a response signal. Receives a concurrent service request to activate a new process to handle this customer request (such as fork, exec in a UNIX system). The new process handles this customer request and does not need to respond to other requests. After the service is complete, close the communication link with the customer for this new process and terminate. 4. Return to the second step and wait for another customer request. 5. Close the server client side: 1. Open a communication channel and connect to a specific port on the host where the server resides; 2. Send a service request message to the server, wait and receive an answer, continue to make a request ... 3. Close the communication channel and terminate after the request has ended. From the process described above: 1. The role of the client and the server process is asymmetric, so the encoding is different. 2. The service process is generally initiated prior to the customer's request. As long as the system is running, the service process persists until normal or forced termination. After introducing the basics, here are some API functions: Create socket ──socket () the application must first have a socket before using a socket, and the system calls the socket () to provide the application with the means to create the socket, which is called in the following format: Socket PASCAL Far socket (int af, int type, int protocol), the call receives three parameters: AF, type, protocol. Parameter AF specifies the area in which the communication occurs: Af_unix, Af_inet, Af_ns, and so on, while DOS, Windows only supports Af_inet, which is the internetwork zone. Therefore, the address family is the same as the protocol family. The parameter type describes the type of socket to be established. There are three kinds of: first, TCP streaming sockets (SOCK_STREAM) provides a connection-oriented, reliable data transmission service, which is error-free, non-repeatable, and received in order of sending. Internal flow control to avoid data flow overrun, data is considered as a byte stream, no length limit. File Transfer Protocol (FTP) uses streaming sockets. The second is a datagram socket (SOCK_DGRAM) that provides a non-connected service. Packets are sent in a separate package, without error-free guarantees, data may be lost or duplicated, and the order of reception is confusing. The Network File system (NFS) uses a datagram socket. The third is the original socket (SOCK_RAW), which allows direct access to lower-level protocols such as IP and ICMP. Often used to verify a new protocol implementation or to access new devices that are configured in an existing service. Parameter ProTocol describes the specific protocol used by the socket, or 0 if the caller does not want to specifically specify the protocol used, using the default connection mode. Based on these three parameters, a socket is established and the corresponding resource is assigned to it, and an integer socket size is returned. Therefore, the socket () system call actually specifies the "protocol" element in the related five-tuple. Specify local address ──bind () when a socket is created with a socket (), there is a namespace (address family), but it is not named. Bind () Ties the socket address (including the local host address and local port address) to the created socket size, assigning the name to the socket to specify local semi-correlation. Its invocation format is as follows: int PASCAL far bind (socket s, const struct SOCKADDR FAR * name, int namelen); The parameter S is the socket descriptor (socket size) returned by the socket () call and not connected 。 The parameter name is the local address (first name) assigned to the socket s, and its length is variable, and the structure varies with the communication domain. Namelen indicates the length of name. If no error occurs, bind () returns 0. Otherwise, return socket_error. Establish socket connection ──connect () and accept () These two system calls are used to complete a complete correlation establishment where connect () is used to establish the connection. A non-connected socket process can also call connect (), but there is no actual message exchange between the processes, and the call is returned directly from the local operating system. The advantage of this is that the programmer does not have to specify the destination address for each data, and if a datagram is received, its destination port does not establish a "connection" with any socket, it can be judged by the operation of the end of the discipline. The Accept () is used to cause the server to wait for the actual connection from a client process. The call format for connect () is as follows: int PASCAL far connect (SOCKET s, const struct SOCKADDR FAR * name, int namelen), and parameter S is the local socket descriptor to establish the connection. The parameter name indicates a pointer to the address structure of the other socket. The length of the other socket address is explained by Namelen. If no error occurs, connect () returns 0. Otherwise the return value is Socket_error. In a connection-oriented protocol, this call causes the connection between the local system and the external system to actually be established. Because the address family is always included in the first two bytes of the socket address structure and is associated with a protocol family through the socket () call. So bind () and connect () do not require a protocol as a parameter. AcceptThe invocation format is as follows: Socket PASCAL far accept (socket s, struct sockaddr far* addr, int far* addrlen), parameter S is a local socket descriptor and should be used before the parameter used for the Accept () call The Listen () is called first. Addr A pointer to the client socket address structure that is used to receive the address of the connection entity. The exact format of the addr is determined by the address family established when the socket was created. Addrlen the length (in bytes) of the client-side socket address. If no error occurs, accept () returns a value of the socket type that represents the descriptor of the received socket. Otherwise the return value is Invalid_socket. Accept () is used for connection-oriented servers. Parameters addr and Addrlen store the address information of the client party. Before the call, the parameter addr points to an address structure with an initial value of NULL, while the initial value of Addrlen is 0, and after the call to accept (), the server waits for a client connection request from a socket numbered s, and the connection request is made by the client's connect () call. When a connection request arrives, the Accept () call places the first client socket address and length on the request connection queue into addr and Addrlen, and creates a new socket size that has the same characteristics as S. The new socket can be used to process server concurrent requests. Four sockets system calls, Sockets (), bind (), connect (), accept (), can complete a completely five-dollar related establishment. The socket () specifies the protocol element in a five-tuple, which is used in relation to whether it is a client or server, or whether it is connection-oriented. Bind () specifies a local two-dollar, local host address and port number in a five-tuple, and its usage is related to whether it is connection-oriented: Bind () is called on the server side, regardless of whether it is connection-oriented, or bind () is not called with connection-oriented, and can be done automatically via connect (). With no connection, the client must use BIND () to obtain a unique address. Listener Connection ──listen () This call is used to target the connection server, indicating that it is willing to receive connections. Listen () needs to be called before accept () with the following format: int PASCAL Far Listen (socket s, int backlog), the parameter S identifies a locally established, not yet connected socket size, and the server is willing to receive requests from it. The backlog represents the maximum length of the request connection queue and is used to limit the number of queued requests, currently allowing a maximum value of 5. If no error occurs, listen () returns 0. Otherwise it returns Socket_erroR. Listen () can complete the required connection for socket s that have not called bind () during the call process and establish a backlog-length request connection queue. Calling Listen () is the third step in the four steps a server receives for a connection request. It allocates a stream socket in the calling socket () and calls bind () to the s assigned to a name, and must be called before accept (). Data transfer ──send () and recv () when a connection is established, it can be transferred. Common system calls have Send () and recv (). The Send () call is used to transmit output data on the specified concatenated datagram or stream socket for the key age, in the following format: int PASCAL far send (SOCKET s, const char far *buf, int len, int flags), parameter s is a connected The local socket descriptor. The BUF points to a pointer to the buffer that holds the data, which is specified in length by Len. Flags specifies the mode of transmission control, such as whether to send out-of-band data. If no error occurs, send () returns the total number of bytes sent. Otherwise it returns SOCKET_ERROR. The recv () call is used to receive input data on a connected datagram or stream socket specified by S, in the following format: int PASCAL far recv (SOCKET s, char far *buf, int len, int flags), parameter s is a connected socket descriptor. The BUF points to the pointer that receives the input data buffer, whose length is specified by Len. Flags specifies the mode of transmission control, such as whether to receive out-of-band data. If no error occurs, recv () returns the total number of bytes received. Returns 0 if the connection is closed. Otherwise it returns SOCKET_ERROR. The input/output multiplexing ──select () Select () call is used to detect the state of one or more sockets. For each socket, this call can request information about a read, write, or Error state. A collection of sockets that request a given State is indicated by a fd_set structure. On return, this structure is updated to reflect the subset of sockets that meet certain criteria, while the Select () call returns the number of sockets that meet the criteria, with the following invocation format: int PASCAL far Select (int Nfds, fd_set FAR * Readfds , Fd_set FAR * Writefds, Fd_set FAR * exceptfds, const struct TIMEVAL FAR * timeout); parameter Nfds indicates that theCheck the value range of the socket descriptor, this variable is generally ignored. The Readfds parameter points to a pointer to a collection of socket descriptors to be read-tested, which the caller wants to read from. The Writefds parameter points to a pointer to the set of socket descriptors to be write-detected. Exceptfds a pointer to a collection of socket descriptors to detect if an error occurred. Timeout points to the maximum time the Select () function waits, or a blocking operation if set to null. Select () returns the total number of socket descriptors that are prepared in the FD_SET structure, or returns SOCKET_ERROR if an error occurs. Closes the socket ──closesocket () closesocket () closes the socket S and releases the resources assigned to the socket, and if s involves an open TCP connection, the connection is freed. The invocation format of Closesocket () is as follows: BOOL PASCAL far closesocket (socket s); The socket descriptor to be closed by the parameter S. If no error occurs, closesocket () returns 0. Otherwise the return value is Socket_error. The above is the socket API some common API functions, below I introduce the C/S mode is the client/server communication mode, the server starts the service and listens in the corresponding port, the client opens the connection, completes the communication link establishment, the two sides carries on the data interaction, finishes closes the socket.

C + + socket

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.