Network socket function | socket, bind, listen, accept, connect

insert image description here

Welcome to follow the blogger Mindtechnist or join [ Linux C/C++/Python Community ] to learn and share Linux, C, C++, Python, Matlab, robot motion control, multi-robot collaboration, intelligent optimization algorithm, filter estimation, multi-sensor information fusion, Knowledge and technology in machine learning, artificial intelligence and other related fields.



Column: "Network Programming"


Socket model creation flow chart

insert image description here

socket function

#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
int socket(int domain, int type, int protocol);

domain:
AF_INET This is most of the protocols used to generate sockets, using TCP or UDP for transmission, and using IPv4 addresses.
AF_INET6 Similar to the above, but to use IPv6 addresses.
AF_UNIX local protocol, used on Unix and Linux systems, is generally used when the client and server are on the same machine.
type:
SOCK_STREAM This protocol is a sequential, reliable, and data-integrated byte-stream-based connection. This is the most used socket type, and this socket uses TCP for transmission.
SOCK_DGRAM This protocol is a connectionless, fixed-length transfer call. The protocol is unreliable and uses UDP for its connections.
SOCK_SEQPACKET This protocol is a two-wire, reliable connection that sends fixed-length data packets for transmission. The package must be completely accepted before it can be read.
The SOCK_RAW socket type provides a single network access. This socket type uses the ICMP public protocol. (Ping and traceroute use this protocol)
SOCK_RDM This type is rarely used and is not implemented on most operating systems. It is provided for the data link layer and does not guarantee the order of data packets.
protocol:
pass 0 to use the default protocol.
Return value:
success: return the file descriptor pointing to the newly created socket, failure: return -1, set errno.
socket() opens a network communication port. If successful, it returns a file descriptor just like open(). The application can use read/write to send and receive data on the network like reading and writing files. If the socket() call fails, then returns -1. For IPv4, the domain parameter is specified as AF_INET. For the TCP protocol, the type parameter is specified as SOCK_STREAM, indicating a stream-oriented transport protocol. If it is a UDP protocol, the type parameter is specified as SOCK_DGRAM, indicating a datagram-oriented transport protocol. The introduction of the protocol parameter is omitted, just specify it as 0.

bind function

#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen);

sockfd:
socket file descriptor.
addr:
Construct an IP address plus port number.
addrlen:
sizeof(addr) length.
Return value:
return 0 on success, -1 on failure, set errno.
The network address and port number monitored by the server program are usually fixed. The client program can initiate a connection to the server after knowing the address and port number of the server program. Therefore, the server needs to call bind to bind a fixed network address and port number. The port number.
The function of bind() is to bind the parameters sockfd and addr together, so that sockfd, a file descriptor for network communication, listens to the address and port number described by addr. As mentioned earlier, struct sockaddr * is a general pointer type. The addr parameter can actually accept sockaddr structures of various protocols, and their lengths are different, so the third parameter addrlen is required to specify the length of the structure. like:

struct sockaddr_in servaddr;
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(6666);

First clear the entire structure, then set the address type to AF_INET, and the network address to INADDR_ANY. This macro represents any local IP address, because the server may have multiple network cards, and each network card may also be bound to multiple IP addresses. The setting can listen on all IP addresses, and it is not determined which IP address to use until a connection is established with a client, and the port number is 6666.

listen function

#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
int listen(int sockfd, int backlog);

sockfd:
socket file descriptor.
backlog:
The sum of the number of connections that queued to establish the 3-way handshake queue and the 3-way handshake queue just established.
View system default backlog

cat /proc/sys/net/ipv4/tcp_max_syn_backlog

A typical server program can serve multiple clients at the same time. When a client initiates a connection, the accept() called by the server returns and accepts the connection. If there are a large number of clients initiating connections and the server has no time to process them, the clients who have not yet accepted The terminal is in the connection waiting state, listen() declares that sockfd is in the listening state, and allows at most backlog clients to be in the connection waiting state, and ignores if more connection requests are received. listen() returns 0 on success and -1 on failure.

accept function

#include <sys/types.h> 		/* See NOTES */
#include <sys/socket.h>
int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);

sockdf:
socket file descriptor.
addr:
outgoing parameter, return link client address information, including IP address and port number.
addrlen:
Pass in and out parameters (value-result), pass in the size of sizeof(addr), when the function returns, return the size of the address structure actually received.
Return value:
successfully returns a new socket file descriptor for communicating with the client, fails to return -1, sets errno
After the three-way handshake is completed, the server calls accept() to accept the connection, if there is no client when the server calls accept() If there is a connection request from the client, it will block and wait until a client connects. addr is an outgoing parameter, and accept() returns the address and port number of the outgoing client. The addrlen parameter is an incoming and outgoing parameter (value-result argument). What is passed in is the length of the buffer addr provided by the caller to avoid buffer overflow problems, and what is passed out is the actual length of the client address structure (with may not fill the buffer provided by the caller). If you pass NULL to the addr parameter, it means you don't care about the client's address.
Our server program structure is like this:

while (1) {
    
    
	cliaddr_len = sizeof(cliaddr);
	connfd = accept(listenfd, (struct sockaddr *)&cliaddr, &cliaddr_len);
	n = read(connfd, buf, MAXLINE);
	......
	close(connfd);
}

The whole is a while endless loop, each loop handles a client connection. Since cliaddr_len is an incoming and outgoing parameter, the initial value should be reassigned before each call to accept(). The parameter listenfd of accept() is the previous listening file descriptor, and the return value of accept() is another file descriptor connfd, and then communicate with the client through this connfd, and finally close connfd to disconnect, instead of Close listenfd, and go back to the beginning of the loop again. listenfd is still used as the parameter of accept. accept() returns a file descriptor on success, and -1 on error.

connect function

#include <sys/types.h> 					/* See NOTES */
#include <sys/socket.h>
int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen);

sockdf:
socket file descriptor.
addr:
Incoming parameters, specifying server-side address information, including IP address and port number.
addrlen:
Pass in parameters, pass in sizeof(addr) size.
Return value:
return 0 on success, -1 on failure, set errno.
The client needs to call connect() to connect to the server. The parameter forms of connect and bind are the same. The difference is that the parameter of bind is its own address, while the parameter of connect is the address of the other party. connect() returns 0 on success and -1 on error.


insert image description here
insert image description here


Guess you like

Origin blog.csdn.net/qq_43471489/article/details/131325527