/**
* Function: Create socket specifying protocol and type at the same time
* #include <sys/socket.h>
*family (protocol Cluster): Af_inet (IPV4 protocol) AF_INET6 (IPV6 protocol)
*type (socket type): Sock_stream (streaming sockets) TCP communication usage
SOCK_DGRAM (datagram socket) UDP communication uses
Sock_raw (Original socket)
*protocol: If the socket type is not the original socket, then this parameter is 0.
* 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. The main is the server side socket needs to bind, the client socket generally do not need to bind, the kernel will automatically assign the address to the socket
*sockfd:socket () function successfully returned file descriptor
*MY_ADDR: Binding a struct that holds address information
*addrelen: The size of the storage address information structure body
* Return value: Success: 0
Failed:-1
*int bind (int sockfd,struct sockaddr *my_addr,int addrlen);
*/
struct sockaddr{
unsigned short sa_family; Protocol Cluster AF_XXX
Char sa_data[14]; 14-byte Protocol address
};
struct sockaddr_in{
short int sin_family; Protocol Cluster
unsigned short int sin_port; Port number short integer accounted for 2 bytes 16 bits
struct IN_ADDR sin_addr; IP address accounted for 4 bytes 32 bits
unsigned char sin_zero[8]; Padding 0, accounting for 8 bytes keep struct sockaddr and struct sockaddr_in struct body size same
};
struct in_addr{
unsigned long s_addr; 32-bit IP address
};
Typically, a struct sockaddr_in is used to save a network address, which is strongly converted to a struct SOCKADDR type pointer when used.
/**
* #include <sys/socket.h>
* Function: The client establishes a connection to the server
*int Connect (int sockfd,struct sockaddr *serv_addr,int addrlen);
* Return value: Success: 0
Failed:-1
*/
/**
* Function: Set socket to listen mode (passive mode), prepare to receive client's request.
*backlog: The maximum number of requests allowed in the request queue, with most system default values of 5.
*int Listen (int sockfd,int backlog);
* Return value: Success: 0
Failed:-1
*/
/**
* Function: Wait and accept the client connection request. After the connection is established, the function returns a new connected socket
*int Accept (int sockfd,struct serveraddr *addr,socklen_t *addrlen);
* Return Value: Success: establishing a well connected socket descriptor
Failed:-1
*/
Functions used by Linux to build servers and clients