Functions used by Linux to build servers and clients
/ * *
* function: create sockets and specify protocol and type at the same time
* # include
* family (protocol suite): AF_INET (IPv4 protocol) AF_INET6 (IPv6 protocol)
* type (socket type): SOCK_STREAM (streaming socket) TCP communication usage
SOCK_DGRAM (Datagram socket) UDP communication usage
SOCK_RAW (original socket)
* protocol: this parameter is 0. 0 if the socket type is not the original socket.
* return value: success: non-negative socket file descriptor
Failed:-1
* int socket (int family,int type,int protocol)
, /
/ * *
* function: bind the address information stored in the corresponding address structure to the socket. Mainly server-side sockets need to be bound, client sockets generally do not need to bind, the kernel will automatically assign addresses to sockets
The file descriptor returned successfully by the * sockfd:socket () function
* my_addr: bind the structure that stores address information
* addrelen: the size of the storage address information structure
* returned value: success: 0
Failed:-1
* int bind (int sockfd,struct sockaddr * my_addr,int addrlen)
, /
Struct sockaddr {
Unsigned short sa_family; / / protocol suite AF_XXX
Char sa_data [14]; / / 14-byte protocol address
}
Struct sockaddr_in {
Short int sin_family; / / protocol suite
Unsigned short int sin_port; / / Port number short integer occupies 2 bytes and 16 bits
Struct in_addr sin_addr; / / IP address occupies 4 bytes and 32 bits
Unsigned char sin_zero [8]; / / fill 0, occupy 8 bytes to keep struct sockaddr and struct sockaddr_in structures the same size
}
Struct in_addr {
Unsigned long sprinter addr; / / 32-bit ip address
}
Struct sockaddr_in is usually used to save a network address, and when used, it is forcefully converted to a pointer of type struct sockaddr.
/ * *
* # include
* function: client establishes a connection to the server
* int connect (int sockfd,struct sockaddr * serv_addr,int addrlen)
* returned value: success: 0
Failed:-1
, /
/ * *
* function: set the socket to listen mode (passive mode) and prepare to receive requests from the client.
* backlog: the maximum number of requests allowed in the request queue. The default value for most systems is 5.
* int listen (int sockfd,int backlog)
* returned value: success: 0
Failed:-1
, /