One, what is the socket
The socket can be viewed as a programming interface between the user process and the kernel network protocol stack.
Sockets can be used not only for interprocess communication between native computers, but also for interprocess communication between different hosts on a network.
The socket API is an abstract network programming interface that applies to a variety of low-level network protocols, such as IPV4, IPV6, and later Unix Domain sockets. However, the address formats for various network protocols are not the same, as shown in the following illustration:
IPV4 and IPV6 address formats are defined in Netinet/in.h, IPV4 addresses are represented in sockaddr_in structure, including 16-bit port numbers and 32-bit IP addresses, as follows:
struct SOCKADDR_IN {
sa_family_t sin_family;/* address family:af_inet /in_port_t sin_port; /* port in Network byte order
/struct in_addr sin_addr; /* Internet address
/char sin_zero[8];/* Pad bytes, set to zero is OK * *
};
/* Internet address. * *
struct IN_ADDR {
uint32_t s_addr; /* address in network byte order *
/};
The IPV6 address is represented by a SOCKADDR_IN6 structure, including a 16-bit port number, a 128-bit IP address, and some control fields. The address format for UNIX Domain sockets is defined in Sys/un.h and is represented by the SOCKADDR_UN structure. The opening of the various socket address structures is the same, the first 16 bits represent the length of the entire structure (not all UNIX implementations have length fields, such as Linux), and the latter 16 bits represent the address type. The address types of IPv4, IPV6, and UNIX Domain sockets are defined as constant af_inet, Af_inet6, and Af_unix respectively. In this way, you can determine the contents of a structure based on the address Type field, as long as you obtain the first address of a SOCKADDR structure, and you do not need to know which type of SOCKADDR structure is specific. Therefore, the socket API can accept various types of sockaddr struct pointers, such as bind, accept, connect, and so on, that the parameters of these functions should be designed to be void * types to accept various types of pointers, but sock The implementation of the API is earlier than ANSI C standardization, and there is no void * type, so the parameters of these functions are represented by the struct sockaddr * type, which is the generic address structure, as follows:
struct SOCKADDR {
sa_family_t sin_family;
Char sa_data [14];
};
Sin_family: Specify the Address family
Sa_data: It is decided by the sin_family its form.
To force type conversions before passing arguments, for example:
struct sockaddr_in servaddr;
* * Initialize SERVADDR *
/bind (listen_fd, struct sockaddr *) &servaddr, sizeof (SERVADDR));