UNPV1 the Fourth chapter: Basic TCP set interface programming

Source: Internet
Author: User

1 socket function

In order to perform network I/O, the first thing a process must do is call the socket function, specifying the desired type of communication protocol

#include <sys/socket.h>int socket (intintint protocol);//返回:若成功则为非负描述符,若出错则为-1

Where family indicates the protocol family, the type parameter specifies the socket type, the protocol parameter should be set to a certain (see) protocol type literal, or set to 0 to select the system default values for the given family and type combinations
Combination of the family and type parameters in the socket function

2 Connect function

TCP client uses the Connect function to establish a connection to the TCP server

#include <sys/socket.h>int connect(intconststruct sockaddr *servaddr, socklen_t addrlen);                //返回:若成功则为0,若出错则为-1

SOCKFD is the socket descriptor returned by the socket function, and the remaining 2 parameters are a pointer to the socket address structure and the size of the structure. The Connect function fires the three-time handshake of TCP and returns only if the connection is successful or an error occurs in the following cases:
1). If the TCP client does not receive a response from the SYN packet, a etimedout error is returned. If the function is called, the kernel sends a SYN, if there is no response, wait for 6s and then send one, if still not responding, wait for 24s to send another, if the total wait for 75s after the response message is still not received (depending on the kernel).
2). If the response time RST indicates that the server host does not have a process waiting on the port we specify, the customer returns a econnrefused error immediately after receiving the RST packet.
3). If the customer sends a SYN in the middle of the router caused a "Destination unreachable" ICMP error, in the first case, continue to send Syn, if not received within the specified time response, The ICMP error is returned as a Ehostunreach or Enetunreach error.
The function connect causes the closed state (which is always the state after the socket) to go to the syn_sent state, if it succeeds and then goes to the established state.

3 bind function

The BIND function assigns a local protocol address to a socket. For Internet Protocol, the protocol address is an IP address and a port number

#include <sys/socket.h>int bind (intconststruct sockaddr *myaddr, socklen_t addrlen);//返回,成功为0,出错为-1

The parameter SOCKFD is the socket descriptor returned by the socket function, MYADDR is a pointer to the protocol-specific address structure, the third parameter is the length of the address structure, and for TCP, calling the BIND function can specify a port, or specify an address, or both. can also not be specified.

4 Listen function

The function listen is only called by the TCP server, which does two events:
1). When a function socket creates a socket interface, it is assumed to be an active socket interface, which means that it is a client socket interface that will invoke connect to initiate a connection, and the function listen converts the disconnected socket interface into a passive socket, indicating that the kernel should accept a connection request to this set of interfaces.
2). The second function of the function specifies the maximum number of connections that the kernel queues for this set of interfaces

#include <sys/socket.h>int listen (intint backlog);//返回,成功为0,出错-1 

To understand the backlog parameters, we need to know that the kernel maintains 2 queues for any given listener socket:
1). The connection queue is not completed. The TCP three handshake between the client and the server was not completed.
2). The connection queue has been completed. The three-time handshake for TCP has been completed and is in the established state.

about the processing of two queues:
The backlog parameter of the 1.listen function has been specified as the maximum value of the sum of two queues
2. Implementation from Berkeley adds a blur factor to the backlog, multiplying it by 1.5 to get the maximum length of the outstanding queue
3. Do not define the backlog as 0, because different implementations have different interpretations of this
4. Under the premise of normal completion of the three-way handshake (that is, there is no loss of subsection, thus no retransmission), any item in which the connection queue is not completed is a RTT, and the value of the RTT depends on the specific client and server
When a client SYN arrives, if these queues are full, TCP ignores the sub-section, that is, does not send the RST
5. After the three-way handshake is complete, but the data that arrives before the server calls accept should be arranged by the server TCP, the maximum amount of data is the accepted buffer size of the corresponding connected socket

5 Accept function

The Accept function is called by the TCP server to return the next completed connection from the completed Connection queue column header, and the process will be put to sleep if the connection queue has been completed empty

#include <sys/socket.h>int accept (intstruct sockaddr *cliaddr, socklen_t *addrlen);//返回:若成功为非负描述符,出错为-1

Parameters Cliaddr and Addrlen return the protocol address of the connected client, and if the client's protocol address is not interested, the parameter Addrlen is the value-result parameter, the size of the incoming socket address structure at the time of the function call, When the function returns, its value is the exact number of bytes that the kernel holds in the socket's address structure.
If the accept succeeds, then its return value is a new descriptor automatically generated by the kernel, representing the TCP connection to the returned client, generally we call the Accept function the first parameter to be a listener socket descriptor (created by the socket, Then used as the descriptor for the first parameter of bind and listen), which is called the return value of the connected socket descriptor
The Accept function returns a maximum of three values: one may be a new socket descriptor or an integer that indicates an error, the protocol address of the client process (as indicated by the CLIADDR pointer), and the size of the address (as indicated by the Addrlen pointer).

6 fork and EXEC functions

The fork function, which includes a variety of variants that some systems might provide, is the only way to derive a new process from UNIX.

#include <unistd.h>pid_t fork(void);//返回:在子进程中为0,在父进程中为子进程的ID,若出错为-1

The hardest part of understanding fork is that it is called once, it returns two times, and the return value itself tells whether the current process is a child or parent process.
Fork returns 0 in the child process, the ID number of the child process is returned in the parent process because a child process has only one parent process, and the parent process ID can be obtained by calling Getppid in the child process. However, the parent process can have more than one child process, and there is no way to get the ID of the child process in the parent process, and if the parent process wants to track the child process, it must save the child process's ID after the fork returns.
2 Typical uses of the fork function:
(1) A process creates a copy of itself, and each copy performs its own operation.
(2) A process wants to execute another program, then it calls the fork function to create a copy of itself, and then calls the EXEC function to replace itself with a new program.
The difference between the following exec functions is that
A. Whether the program to be executed is specified by file name or by path name
B. The parameters of the new program are listed or referenced by an array of pointers
C. Passing the environment of the calling process to a new program or assigning a new environment to the Metro Coarse

#include <unistd.h>intEXECL (Const Char*pathname,Const Char*arg0, .../* (char *) 0 */);intEXECV (Const Char*pathname,Char*ConstArgv[]);intExecle (Const Char*pathname,Const Char*arg0, .../* (char *) 0, char *const envp[] */);intExecve (Const Char*pathname,Char*ConstArgv[],Char*ConstEnvp[]);intEXECLP (Const Char*filename,Const Char*arg0, .../* (char *) 0 */);intEXECVP (Const Char*filename,Char*ConstArgv[]);

In addition, the descriptor that the process opens before calling exec usually continues to remain open across exec.

7 Close function

The usual Unix close function is also used to close the socket and terminate the TCP connection

#include <unistd.h>int close (int sockfd);         //返回:若成功为0,出错为-1

The default behavior of the close one TCP socket is to set the socket to closed and then immediately return to the calling process, and in the concurrent server, fork a child process copies all the descriptors that the parent process created before the fork, and the reference count of the corresponding descriptor increases by 1 after the copy completes, calling close Causes the descriptor's reference count to be reduced by 1, and once the descriptor's reference count is 0, the kernel closes the socket. When the descriptor reference count of a socket is still greater than 0 when the close is called, the terminating sequence of TCP is not raised. If you want to send fin on a TCP connection, you can call the shutdown function.

8 GetSockName and Getpeername functions

The GetSockName function returns the local protocol address associated with a socket, and the Getpeername function returns the address of the foreign protocol associated with a socket

#include <sys/socket.h>intgetsockname(int*localaddr*addrlen);intgetpeername(int*peeraddr*addrlen);//返回值:成功返回0,出错返回-1*addrlen是值-结果参数

These two functions are needed for the following reasons:
1). On a TCP client that does not call bind, when Connect returns successfully, GetSockName is used to return the local IP address and local port number that the kernel gave to the connection.
2). After the port number 0 is called, GetSockName is used to return the local port number given by the kernel
3). Once the connection is established, Getpeername can be invoked to obtain the client's identity.
4). On a TCP server that calls bind with a wildcard IP address, once the connection to a client is established (accept returns successfully), GetSockName can be used to return the local IP address that the connection was given by the kernel, in such a call, The socket descriptor parameter must be a descriptor of a connected socket, not a descriptor for a listening socket
5). When a server is called by a process that calls exec to execute a program, the only way it can acquire a client's identity is to call Getpeername

UNPV1 the Fourth chapter: Basic TCP set interface programming

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.