Socket function, in order to perform network I/O, the first thing a process must do is call the socket function and specify the type of communication protocol.
#include <sys/socket.h>int socket (intintint/// successfully returns non-negative descriptor, Error-1
Where the family parameter indicates the protocol family, Af_inet (IPV4), Af_inet6 (IPV6), the type parameter indicates the types of sockets, Sock_stream (Byte stream), Sock_dgram (packets).
Connet function, the TCP client uses the Connet function to establish a connection to the TCP server.
#include <sys/socket.h>int connect (intconststruct sockadd* servaddr, Socklet_addrlen); // successful return 0, error-1
SOCKFD is the socket descriptor returned by the socket function, second, the third parameter is a pointer to the socket address structure and the size of the structure. The servaddr must contain the IP address and port number of the server.
The client does not have to call the BIND function before calling the Connect function, the kernel determines the source IP and selects a temporary port.
Bind function, the BIND function assigns a local address protocol to a socket.
#include <sys/socket.h>int bind (int sockfd,conststruct sockaddr* myaddr, Socklen_t Addrlen); // successful return 0, error-1
MYADDR is a pointer to the address structure of a particular protocol, AH DDR Addrlen is the length of the address structure. For TCP, call the BIND function to set the IP address, port number.
Listen function, called only by the TCP server, when the socket function creates a socket, the default is to create an active socket, which is a client socket that will invoke connect to initiate the connection. The Listen function converts an unbound socket into a passive socket, indicating that the kernel should accept connection requests to that socket.
#include <sys/socket.h>int Listen (intint backlog); // successful return 0, error-1
The backlog is the sum of the queue lengths that are not completed for the connection queue and completed but not applied by the process.
The Accept function, called by the TCP server, returns the next completed connection from the completed connection queue header, and if the completed connection queue is empty, the process is blocked.
#include <sys/socket.h>int accept (intstruct sockaddr*cliaddr, socklen_t *addrlen) // successful non-negative descriptor, error 1
The parameters cliaddr and Addrlen are used to return the protocol address of the connected peer process. If the accept succeeds, then the return value is a completely new socket generated automatically by the kernel, representing the TCP connection to the client.