C ++ socket programming BASICS (theoretical)

Source: Internet
Author: User
Tags file transfer protocol

For socket, I don't want to know its history here. I just want to say that it is a process communication method at the time, in short, some API functions of the network library can be called to exchange data between processes distributed across different hosts.

In socket, we need to understand the following definition concepts:

First, IP Address: I think it is easy to understand that the network address assigned to the local host according to the TCP/IP protocol needs to communicate with the two processes, if any process needs to know the location of the Communication peer and how the location is determined, the IP address of the Communication peer should be used.

Second, the port number is used to identify the local communication process and facilitate the OS to submit data. that is to say, the process specifies the network IP address of the other process, but this IP address is only used to identify the host where the process is located. How to find the process running on this host, then use the port number.

3. connection: the communication link between two processes.

4. Semi-correlation: using a triple in the network can uniquely identify a process in the world:

(Protocol, local address, local port number)

Such a triple is called a semi-correlation, which specifies each half of the connection.

5. Full correlation

A complete inter-network process communication must be composed of two processes and can only use the same high-level protocol. That is to say, it is impossible for one end of the communication to use the TCP protocol, while the other end to use the UDP protocol. Therefore, a complete inter-network communication requires a quintuple:

(Protocol, local address, local port number, remote address, and remote port number)

Such a quintuple is called association, that is, two half-correlation protocols can be combined into an appropriate correlation, or completely specify to form a connection.

Customer/Server mode

In TCP/IP network applications, the main mode of interaction between two processes is the customer/Server mode.
(Client/server model), that is, the customer sends a service request to the server. After receiving the request, the server provides the corresponding service. The customer/Server mode is based on the following two points:
First, the reason for establishing a network is that the hardware and software resources, computing power, and information in the network are not equal and need to be shared to create a host with many resources to provide services, customer request service with few resources
. Second, inter-network process communication is completely asynchronous, and there is no parent-child relationship between processes that communicate with each other without sharing the memory buffer. Therefore, a mechanism is required to establish a connection between processes that want to communicate with each other, is the number of two
Data Exchange provides synchronization, which is the TCP/IP of the Ji households/Server mode.

The customer/Server mode takes the active Request Method in the key discipline process:

First, the server must start and provide the corresponding services according to the request:

1. Open a channel and inform the local host that it is willing to receive customer requests at a recognized address (port, for example, FTP is 21;

2. Wait for the customer's request to reach the port;

3. Receive a duplicate service request, process the request, and send a response signal. To receive a concurrent service request, activate a new process to process the request (such as fork and exec in UNIX ). The new process processes this customer request and does not need to respond to other requests. After the service is completed, close the communication link between the new process and the customer and terminate the process.

4. Return step 2, waiting for another customer's request.

5. Disable the server

Customer:

1. Open a channel and connect to the specific port of the host where the server is located;

2. Send a service request message to the server, wait for and receive the response; Continue to make the request ......

3. After the request ends, the communication channel is closed and terminated.

We can see from the process described above:

1. The role of the client and server processes is non-symmetric, so the encoding is different.

2. Service processes are generally initiated upon requests from Ji households. As long as the system is running, the service process persists until it is normal or forced to terminate.

After introducing the basic knowledge, the following describes some API functions:

Create socket -- socket ()

Before using a socket, an application must first have a socket. The system calls socket () to provide the application with the means to create a socket. The call format is as follows:

Socket Pascal far socket (int af, int type, int Protocol );

The
The call must receive three parameters: AF, type, and protocol. The AF parameter specifies the region where communication occurs, such as af_unix, af_inet, and af_ns, While DOS,
Windows only supports af_inet, which is an Internet region. Therefore, the address family is the same as the protocol family. The type parameter describes the type of the socket to be created. There are three types: one is TCP stream
_Stream provides a connection-oriented and reliable data transmission service. It sends data in error-free and repeat-re-transmission order. Internal traffic control to avoid excessive Data Flow
Data is considered as a byte stream with no length limit. The file transfer protocol (FTP) uses a streaming socket.

Second, the datagram socket (sock_dgram) provides a connectionless
Service. Data packets are sent in the form of independent packets. No error guarantee is provided. data may be lost or duplicated, and the receiving order is disordered. Network File System (NFS) uses a datagram socket. Third, original socket
(Sock_raw) This interface allows direct access to lower-layer protocols, such as IP and ICMP. It is often used to test new protocol implementations or access new devices configured in existing services. The Protocol Parameter
Indicates the specific protocol used by the socket. If the caller does not want to specify the protocol used, the value is set to 0 and the default connection mode is used. Create a socket based on the three parameters and allocate the corresponding resources
It returns an integer socket number. Therefore, the socket () System Call actually specifies the "protocol" dollar in the related quintuple.

Specify the local address -- BIND ()

After a socket is created with socket (), a namespace (address family) exists, but it is not named. BIND () associates the socket address (including the local host address and local port address) with the created socket number, that is, assign the name to the socket to specify the local semi-correlation. The call format is as follows:

Int Pascal far BIND (socket S, const struct sockaddr far * Name, int namelen );

Parameter
The number of S is the socket Descriptor (socket number) returned by the socket () call and not connected ). The parameter name is the local address (name) assigned to socket S. Its length is variable, and the structure is subject to communication.
The domain is different. Namelen indicates the name length. If no error occurs, BIND () returns 0. Otherwise, socket_error is returned.

Establish a socket connection -- connect () and accept ()

This
Two system calls are used to complete a complete related establishment, and connect () is used to establish a connection. A connectionless socket process can also call connect (), but there is no
For actual Packet Exchange, the call will be directly returned from the local operating system. The advantage of this is that the programmer does not need to specify the destination address for each data, and if a datagram is received, its destination port is not connected to any socket
By establishing a "connection", you can determine that this end is subject to discipline and operation. And accept () is used to make the server wait for the actual connection from a customer process.

The call format of connect () is as follows:

Int pascal far connect (SOCKET s, const struct sockaddr FAR * name, int namelen );

The parameter s is the local socket descriptor to establish a connection. The parameter name indicates the pointer indicating the structure of the socket address of the other party. The length of the socket address of the other party is described by namelen.

If no error occurs, connect () returns 0. Otherwise, SOCKET_ERROR is returned. In the connection-oriented protocol, this call causes the actual connection between the local system and the external system.

Because the address family is always included in the first two bytes of the socket address structure, and is related to a protocol family through socket () calls. Therefore, the bind () and connect () protocols are not required as parameters.

The call format of accept () is as follows:

Socket pascal far accept (SOCKET s, struct sockaddr FAR * addr, int FAR * addrlen );

Parameter
The number of s is the local socket descriptor. You should call listen () before using the parameter called by accept (). The addr pointer to the client's socket address structure to receive the connection
Body address. The exact addr format is determined by the address family created at the socket creation. Addrlen is the length (in bytes) of the client socket address ). If no error is reported
Generate, accept () returns a socket type value, indicating the descriptor of the received socket. Otherwise, the returned value is invalid_socket.

Accept ()
For connecting servers. The ADDR and addrlen parameters store the customer's address information. Before the call, the ADDR parameter points to an address structure with an empty initial value, while the initial value of addrlen
The start value is 0. After accept () is called, the server waits for the client connection request to be accepted from the socket number S, and the connection request is sent by the client's connect () call. When there is a connection, please
When the request arrives, the accept () call puts the first client socket address and length in the request connection queue into ADDR and addrlen, and creates a new socket with the same features as S.
. The new socket can be used to process concurrent requests from the server.

Four socket system calls, socket (), BIND (),
Connect (), accept (), you can complete a fully quintuple-related establishment. Socket () specifies the Protocol element in the quintuple. Its usage is similar to whether it is a customer or server, or whether it is a plane.
To the connection. BIND () specifies the Local Binary In the quintuple, that is, the address and port number of the local host. Its usage is related to whether connection is oriented.
BIND (). If connection orientation is adopted, BIND () can be called instead of Connect. If no connection is used, the customer must use bind () to obtain a unique
.

Listener ── listen ()

This call is intended for connection servers, indicating that it is willing to receive connections. Listen () must be called before accept (). The call format is as follows:

Int Pascal far listen (socket S, int backlog );

The parameter s identifies a locally established, unconnected socket number, and the server is willing to receive requests from it. Backlog indicates the maximum length of the Request connection queue. It is used to limit the number of requests in the queue. Currently, the maximum value is 5. If no error occurs, listen () returns 0. Otherwise, it returns SOCKET_ERROR.

During the execution of the call, listen () can complete the required connection for the socket s without calling bind () and establish a request connection queue with the length of backlog.

Calling listen () is the third step in the four steps in which the server receives a connection request. It allocates a stream socket when socket () is called, and CALLS bind () after giving s a name, and must be called before accept.

Data transmission-send () and recv ()

After a connection is established, data can be transmitted. Common system calls include send () and recv ().

The send () call is used to send output data on the connected datagram or stream socket specified by the key discipline s. The format is as follows:

Int pascal far send (SOCKET s, const char FAR * buf, int len, int flags );

The parameter s is the descriptor of the connected local socket. The buf pointer to a buffer with sent data. Its length is specified by len. Flags specifies the transmission control mode, 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 the connected datagram or stream socket specified by s. The format is as follows:

Int pascal far recv (SOCKET s, char FAR * buf, int len, int flags );

Parameter
The number of s is the connected socket descriptor. The buf pointer to the buffer for receiving input data. Its length is specified by len. Flags specifies the transmission control mode, such as whether to receive out-of-band data. If
If no error occurs, recv () returns the total number of bytes received. If the connection is closed, 0 is returned. Otherwise, it returns SOCKET_ERROR.

Multiplexing of input/output -- select ()

Select ()
Call is used to detect the status of one or more sockets. For each socket, this call can request read, write, or error information. The socket set in the given Request status is composed of an fd_set
Structure indication. This structure is updated to reflect the subset of sockets that meet specific conditions. At the same time, the select () call returns the number of sockets that meet the conditions. The call format is as follows:

Int pascal far select (int nfds, fd_set FAR * readfds, fd_set FAR * writefds, fd_set FAR * limit TFDs, const struct timeval FAR * timeout );

The nfds parameter indicates the value range of the socket descriptor to be checked. This variable is generally ignored.

Parameter
The number of readfds points to the pointer to the socket descriptor set for read detection, and the caller wants to read data from it. The writefds parameter points to the pointer to the socket descriptor set for write detection.
Exceptfds indicates the pointer to the socket descriptor set to detect for errors. Timeout points to the maximum waiting time of the select () function. If it is set to NULL, It is a blocking operation.
. Select () returns the total number of socket descriptors that have been prepared in the fd_set structure, or returns SOCKET_ERROR if an error occurs.

Close socket-closesocket ()

Closesocket () closes socket s and releases the resources allocated to the socket. If s involves an open TCP connection, the connection is released. Closesocket () is called in the following format:

Bool pascal far closesocket (SOCKET s );

Socket descriptor to be disabled by parameter s. If no error occurs, closesocket () returns 0. Otherwise, SOCKET_ERROR is returned.

The above are some common API functions of SOCKET APIs. Below I will introduce the C/S mode as the client/server communication mode. The server starts the service and listens on the corresponding port, and the client opens the connection, after the establishment of the communication link, both parties interact with each other, and then close the socket.

Now, we will introduce SOCKET basics here.

 

 

Reprinted from: http://blog.csdn.net/hnwanghb/archive/2007/10/06/1813490.aspx



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.