Network programming 4: A brief analysis of the API provided by Linux (development steps for Socket server and client)

A brief analysis of the API provided by Linux (development steps for Socket server and client)

1. Connection protocol: (TCP/UDP)

//创建套接字
#include <sys/types.h>
#include <sys/socket.h>
int socket(int domain,int type,int protocol);
返回sockfd---失败返回-1

domain:
specify the protocol family used, usuallyAF_INET, Represents the Internet protocol family (TCP/IP protocol family);

AF_INET IPV4 Internet domain
AF_INET6 IPV6 Internet domain
AF_UNIX unix domain
AF_ROUTE routing socket
AF_KEY key socket
AF_UNSPEC not specified

The type parameter specifies the type of socket:
SOCK_STREAM:
Streaming socket provides reliable, connection-oriented communication flow, it uses TCP protocol to ensure the correctness and sequence of data transmission
SOCK_DGRAM: The
datagram socket defines a connectionless server. Data is transmitted through independent messages. It is disorderly, does not guarantee reliability, and is error-free. It uses the datagram protocol UDP .
SOCK_RAW:
Allow the program to use the underlying protocol. The original socket runs to directly access the underlying protocol such as IP or ICMP. It is powerful but inconvenient to use. It is mainly used for the development of some protocols .


protocol
is usually assigned the value "0
0 Select the default protocol corresponding to the type type
== IPPROTO_TCP TCP Transmission Protocol ==
IPPROTO_UDP UDP Transmission Protocol
IPPROTO_SCTP SCTP Transmission Protocol
IPPROTO_TIPC TIPC Transmission Protocol

2. Assignment function of IP number, port number and corresponding description word: bind() function

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

The bind() function assigns a specific address in an address family to the socket. For example, corresponding to AF_INET and AF_INET6 is to assign an ipv4 or ipv6 address and port number combination to the socket.

Function: Used to bind IP address and port number to socketfd
parameters:
sockfd: The socket description word, which is created by the socket() function and uniquely identifies a socket. The bind() function will bind a name to this descriptor.
addr: A const struct sockaddr * pointer, pointing to the sockfd to be boundProtocol address
addrlen: Corresponds to the length of the address.

Protocol address structureIt varies according to the address protocol family when the socket is created. For example, ipv4 corresponds to:

struct sockaddr_in {
    
    
    sa_family_t    sin_family; //协议族
    in_port_t      sin_port;   //端口号
    struct in_addr sin_addr;   //IP地址结构体
};
struct in_addr {
    
    
    uint32_t       s_addr;     /* address in network byte order */
};

Usually the server will bind a well-known address == (such as ip address + port number) == when the server is started, which is used to provide services, and the client can connect to the server through it; the client does not need to be specified, and the system automatically Assign a port number and its own ip address combination. This is why usually the server will call bind() before listen, but the client will not call it. Instead, the system randomly generates one when connect().

3.listen() monitoring function, connect() connection function

If as a server, after calling socket() and bind(), listen() will be called to monitor the socket. If the client calls connect() to send a connection request at this time, the server will receive the request.

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

The first parameter of the listen function is the one to be monitoredsocket description word, The second parameter is the queue that the corresponding socket can queueMaximum number of connections. The socket created by the socket() function is of an active type by default, and the listen function turns the socket into a passive type and waits for the client's connection request.

The first parameter of the connect function isThe socket description of the client, The second parameter isThe socket address of the server, The third parameter is the socket addresslength. The client establishes a connection with the TCP server by calling the connect function.
  
4.accept() receiving request function

After the TCP server calls socket(), bind(), and listen() in turn, it will listen to the specified socket address. After the TCP client calls socket() and connect() in turn, it sends a connection request to the TCP server. After the TCP server listens to the request, it will call the accept() function to receive the request, so that the connection is established. After that, you can start network I/O operations, that is, read and write I/O operations similar to ordinary files.

#include <sys/types.h> 
#include <sys/socket.h>
int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen); //返回连接connect_fd

The three parameters of the function are:

sockfd: is the listening socket explained above. This socket is used to monitor a port. When a client connects to the server, it uses this port number, and this port number is currently connected to this socket Associated. Of course, the client does not know the details of the socket, it only knows an address and a port number.
addr: This is a result parameter, which is used to receive a return value. This return value specifies the address of the client. Of course, this address is described by a certain address structure. The user should know what kind of address structure this one is. If you are not interested in the customer's address, you can set this value to NULL.
len: As everyone thinks, it is also the parameter of the result. It is used to accept the size of the above addr structure. It indicates the number of bytes occupied by the addr structure. Similarly, it can also be set to NULL.

If accept returns successfully, the server and the client have correctly established a connection, and the server completes the communication with the client through the socket returned by the accept.

note:
Accept will block the process by default until a client connection is established and returns. It returns a newly available socket, which is a connection socket.

At this point we need to distinguish between two types of sockets:

Listening socket: The listening socket is just like the accept parameter sockfd. It is the listening socket. After the listen function is called, the server starts to call the socket() function. It is called the listening socket descriptor (monitoring socket)
Connect socket: A socket will change from an actively connected socket to a listening socket; and the accept function returns the description of the connected socket (a connected socket), which represents the point where a network already exists connection.

A server usually only creates a listening socket descriptor, which always exists during the life cycle of the server. The kernel creates a connected socket descriptor for each client connection accepted by the server process. When the server completes the service for a certain client, the corresponding connected socket descriptor is closed.

The connection socket socketfd_new does not occupy a new port to communicate with the client, and still uses the same port number as the listening socket socketfd.
  
5.read(), write() and other functions

There are the following groups of network I/O operations:

read()/write()
recv()/send()
readv()/writev()
recvmsg()/sendmsg()
recvfrom()/sendto()

6.close function

int close(int fd);

The default behavior of closing a TCP socket is to mark the socket as closed, and then immediately return to the calling process. The description word can no longer be used by the calling process, which means that it can no longer be used as the first parameter of read or write.

note: The close operation only makes the reference count of the corresponding socket description word -1, and only when the reference count is 0, will it trigger the TCP client to send a connection termination request to the server.

7. Address translation API:

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int inet_aton(const char *cp, struct in_addr *inp);
//把字符串形成的“192.168.1.123”转为网络能识别的格式
char *inet_ntoa(struct in_addr in);
//把网络格式的ip地址转化为字符串形式

8. Endian conversion API:

#include <arpa/inet.h>
uint32_t htonl(uint32_t hostlong);//返回网络字节序的值
uint16_t htons(uint16_t hostshort);//返回网络字节序的值
uint32_t ntohl(uint32_t netlong);//返回主机字节序的值uint32_t
uint16_t ntohs(uint16_t netshort);//返回主机字节序的值

h represents host, n represents net, s represents short (two bytes), and l represents long (4 bytes); the conversion between host byte order and network byte order can be realized through the above four functions. Sometimes it can be usedINADDR_ANY, INADDR_ANY specifies the address for the operating system to obtain.

The code writing between the client and the server can be completed through the above API

See the next section for code implementationNetwork programming 5explain

Guess you like

Origin blog.csdn.net/weixin_40734514/article/details/108555217