Socket for network programming

TCP client:
1. Establish connection socket, set IP and port monitoring, socket ()
2. Establish connection
3.write () Obtain network stream object send data
4.read () Acquire network stream object receive data
5. Close socket

TCP server
1. Establish a port listening socket ()
2. Bind the specified port bind ()
3. listen for port monitoring
4. accept () blocking until there is a client access
5. read () to obtain the data sent by the client
6. write () sends return data
7.close closes the port listening
Insert picture description here
function call required by the server to establish a connection with the client

1.
socket function socket function to establish a socket socket

int socket(int family, int type, int protocol);
返回值:成功返回非负描述符,若出错返回 -1;

int family:协议族 (socket 函数的family常值包括:
 AF_INET, AF_INET6, AF_LOCAL, AF_ROUTE, AF_KEY.

int type:套接字类型(SOCK_STREAM, SOCK_DGRAM, SOCK_SEQPACKET, SOCK_RAM)

int protocol:协议类型(IPPROTO_TCP, IPPROTO_UDP, IPPROTO_SCTP

(1) Not all combinations of family and type are valid, so the protocol parameter is generally set to 0 to allow the kernel to automatically match the protocol type to avoid errors.
(2) Address family AF_XXX. Protocol family PF_XXX.
(3) The POSIX specification specifies that the first parameter of the socket function is the PF_ value, and the AF_ value is used for the socket address structure.

2.connect function
TCP client uses connect function to establish connection with TCP server

int connect(int sockfd, const struct sockaddr *servaddr, socklen_t addrlen); 
返回值:  成功返回 0 ,出错返回 -1。

int sockfd: socket函数返回的套接字描述符。

const struct *servaddr: 指向套接字地址结构的指针。

socklen_t addrlen: 套接字地址结构的的大小。

(1) The passed socket address structure must contain the server's IP address and port number.
(2) The client does not have to call the bind function when calling connect. If necessary, the kernel will determine the source IP address and select a temporary port as the source port.
(3) The connect function will stimulate TCP's three-way handshake process.
(4) Several situations when connect returns with error:

  • If the TCP client does not receive a response from the SYN section within the specified time, it returns an ETIMEOUT error
  • If the response to the client's SYN is RST (the other party's connection is reset), it means that the server host has no processes waiting to connect to it on the port we specified. This is a hard error and the customer returns an ECONNREFUSED error as soon as he receives the RST. The three conditions for generating the RST segment are: the destination is a SYN of a port, but there is no server listening on that port; TCP wants to cancel an existing connection; TCP receives a segment on a connection that does not exist at all Festival
  • If the SYN issued by the client triggers a "destination unreachable" ICMP error on an intermediate router, it is considered to be a soft error and the client saves the message in the kernel. And continue to send SYN at a certain time interval, within the specified time has not received a response. The saved message is returned to the process as an EHOSTUNREACH (ENETUNREACH error is outdated ENETUNREACH treated as EHOSTUNREACH) error.

(5) If the connect call fails, the socket descriptor can no longer be used and must be closed

3. The bind function
bind function assigns a local protocol address to a socket. For TCP / IP protocol, the protocol address is the combination of IP address and port number.

int bind(int sockfd, cosnt struct sockaddr *myaddr, socklen_t addrlen);
返回值:成功返回0,出错返回 -1

int sockfd: 由socket函数返回的套接字描述符。

const struct sockaddr *myaddr: 指向特定于协议的套接字地址结构的指针。

socklen_t : 套接字地址结构的大小。

The binding operation involves three objects: socket, address and port. The socket is the subject of binding, and the address and port are the objects bound to the socket.
(1) The bind function can be used to specify both the IP address and port number, or only the IP address or port number.
(2) Except for the RPC server (using the port mapper), all other servers need to call bind to bind at least his service port number.
(3) If the client program does not need to specify a specific port number, then the client program generally does not call the bind function, the kernel will assign an IP address and port number for the client program.
(4) If you call the bind function to bind an IP address belonging to an interface of the machine to the socket: For the client program, this IP address is the source IP address of the datagram sent. For the server, it restricts the server to only receive connections from client programs destined for this IP address.
(5) If the address to be bound is used, bind returns an EADDRINUSE error.
(6) The bind function does not return the bound IP address and port number. You can get this information by calling getsockname.
(7) bind binds different IPs for different servers, you can run multiple server copies on the same multi-homed machine, and each copy serves a specific customer.
(8) Packet's arrival interface and packet's destination IP address, strong-end system model and weak-end system

4. The listen function
listen function is only called by the TCP server.

int listen(int sockfd, int backlog);返回值:成功返回0 出错返回 -1。

int sockfd: socket 函数返回的套接字描述符。

int backlog: 已连接套接字的已完成连接的最大排队数。

(1) The listen function converts an unconnected socket into a passive socket, instructing the kernel to accept connection requests directed to the socket.
(2) The kernel maintains two queues for each listening socket: completed connection queue (incomplete connection queue) and incomplete connection queue (completed connection queue).
(3) Incomplete connection queue: The client's SYN has reached the server, and the server is waiting for the three-way handshake to complete. Such a connection is placed in the incomplete connection queue, and the socket is in the SYN_RCVD state.
(4) Completed connection queue: Three-way handshake connections that have been successfully completed are placed in the completed connection queue. The socket is in ESTABLISHED state.
(5) The backlog parameter specifies the maximum number of completed connections queued by the kernel on a given socket.
(6) The purpose of limiting the number of completed connections is to prevent the kernel from continuing to accept new ones on the socket when the application process listening to a given socket (for whatever reason) stops accepting connections. Connection request.
(7) A large number of outstanding connection queues are handled by the kernel.
(8) When the queue is full, if a new client's SYN arrives at TCP, the SYN is ignored, and generally no error message is returned.

5. accept function The
accept function is called by the TCP server to return the next completed connection from the head of the completed connection queue. If the completed connection queue is empty, the process will be put to sleep (if the socket is the default blocking method) ).

int accept(int sockfd,struct sockaddr *cliaddr, socklen_t *addrlen);
返回值:成功返回非负的描述符,出错返回 -1。

int sockfd : 一个监听套接字。

struct sockaddr *cliaddr : 套接字地址结构的指针,用来返回已连接的对端进程的协议地址。

socklen_t *addrlen: 函数调用的时候是传入的套接字地址结构的大小,函数返回时它的值是内核存放在该套接字地址结构中的确切字节数。

(1) If accept returns successfully, then it will generate a new socket, called a connected socket, which is used to transfer data with the client.
(2) A server usually only creates a listening socket (listening socket), which exists for the entire life cycle of the server.
(3) The kernel creates a connected socket for each client connection accepted by the server process. When the server completes the service to a client, the corresponding socket will be closed.
(4) The accept function returns up to three values: one may be either a new socket descriptor or an integer indicated by the error, the protocol address of the client process, and the size of the address.

6. read (), write () and other functions So
far, the server and the client have established a connection. You can call the network I / O for read and write operations, that is, to achieve communication between different processes in the network.

The read function is responsible for reading content from fd. When the read is successful, read returns the actual number of bytes read. If the returned value is 0, it means that the end of the file has been read. If the error is EINTR, the reading is caused by an interruption. If it is ECONNREST, there is a problem with the network connection.

The write function writes the contents of nbytes bytes in buf to the file descriptor fd. When successful, it returns the number of bytes written. On failure, it returns -1 and sets the errno variable. In network programs, there are two possibilities when we write to the socket file descriptor. 1) The return value of write is greater than 0, indicating that part or all of the data has been written. 2) The returned value is less than 0, and an error has occurred at this time. We have to deal with it according to the type of error. If the error is EINTR, an interruption error occurred during writing. If it is EPIPE, there is a problem with the network connection (the other party has closed the connection).

7. close () function
After the server establishes a connection with the client, it will perform some read and write operations. After the read and write operations are completed, the corresponding socket descriptor will be closed. It is like calling fclose to close the opened file after the operation.

int close(int fd);
close一个TCP socket的缺省行为时把该socket标记为以关闭,
然后立即返回到调用进程。该描述字不能再由调用进程使用,
也就是说不能再作为read或write的第一个参数。

Note: The close operation only makes the reference count of the corresponding socket descriptor -1. Only when the reference count is 0 will the TCP client be triggered to send a connection termination request to the server.

Published 162 original articles · praised 58 · 90,000 views

Guess you like

Origin blog.csdn.net/ThreeAspects/article/details/105570390