Socket address structure

zhaozj2021-02-08  260

The address plays a critical role in the process of establishing socket communication. When designing the TCP / IP network program, you must have a clear understanding of the address structure of the socket. The address data structure of TCP / IP. Struct SockAddr {u_short safamily; / * address family, AF_XXX * / CHAR SA_DATA [14]; / ​​* 14-byte specific protocol address * /} where 14-byte SA_DATA is different from the protocol. In the TCP / IP protocol, the address data structure is: struct in_addr {u_long s_addr; / * 32-bit IP address, network byte order * /}; structure sockaddr_in {short sin_family; / * AF_INET * / U_SHORT SIN_SHORT; / * 16 bits port number, network byte order * / struct in_addr sin_addr; / * 32-bit IP address, network byte order * / char sin_zero [8]; / * Unused * /} network byte order is TCP A data representation format specified in IP, which is independent of the specific CPU type, operating system, etc., which can ensure that data can be properly explained when transmitting between different hosts. Two functions converted from host byte sequence to network byte sequences are as follows: htons (): Convert 16-bit host byte sequential data to network byte order htonl (): 32-bit host byte sequential data conversion For network byte order, the network byte sequentially converts network byte sequence to host byte sequence is: NTOHS (): converts 16-bit network byte sequential data to host byte order NTOHL (): 32 Bit's network byte sequential data conversion to host byte sequence Since the length of the various Socket addresses is large, the address length of the TCP / IP address family is 8 bytes, the XNS address is 14 bytes, the Unix address is uiX, the most Long up to 110 bytes, so you can't define them in a unified format, you need to specify the length of the Socket address in the bind () call. When the bind () parameter is invalid or the port has been used by other programs, the function returns -1, indicating that this Socket is naming failed.

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

New Post(0)