Socket

zhaozj2021-02-16  74

What is Socket? You often hear people talk about "socket", maybe you still don't know its exact meaning. Now let me tell you: it is a way to communicate with the standard UNIX file descriptor and other program. what?

Struct sockaddr.. This structure is a multi-type socket storage socket address information: struct sockaddr {unsigned short sa_family; / * address family, AF_XXX * / CHAR SA_DATA [14]; / ​​* 14 byte protocol address * /}; sa_family It is a variety of types, but in this article "AF_INET". SA_DATA contains target addresses and port information in the socket. It seems that it is a bit unused. In order to handle Struct SockAddr, the programmer creates a parallel structure: struct sockaddr_in ("in" represents "Internet".) Struct SockAddr_in {short int sin_family; / * Communication Type * / unsigned short int sin_port; / * port * / Struct; / * Port * / Struct IN_ADDR SIN_ADDR; / * Internet Address * / unsigned char sin_zero [8]; / * The same length as the SOCKADDR structure; use this data structure to easily handle the basic element of the socket address.

A pointer to the SOCKADDR_IN structure can also be directed to the structure SockAddr and replaced it. In this way, even if Socket () wants Struct SockAddr *, you can still use Struct SockAddr_in and in the final conversion. At the same time, pay attention to the SA_FAMILY in SIN_FAMILY and STRUCT SOCKADDR and can be set to "AF_INET". Finally, sin_port and sin_addr must be a network byte order (NetWork Byte Order)! Htons () - "Host to NetWork Short" HTONL () - "Host to NetWork Long" () - "NetWork to Host Short" Ntohl () - "NetWork to Host Long" Why is in the data structure Struct SockAddr_in In the SIN_ADDR, SIN_PORT needs to be converted to network byte order, while SIN_FAMIL is not needed? The answer is: SIN_ADDR and SIN_PORT package IP and UDP layers in the package. Therefore, they must be a network byte order. However, the SIN_FAMILY domain is only used by the kernel to determine what type of address is included in the data structure, so it must be the unit of this byte. At the same time, SIN_FAMILY is not sent to the network, which can be the native byte order.

转载请注明原文地址:https://www.9cbs.com/read-12517.html

New Post(0)