Linux socket structure definition

Linux in the header file sys / socket.h defines a common socket type structure, to call for a different protocol.

struct sockaddr
{
    unsigned short int sa_family;//套接字协议地址类型
    unsigned char sa_data[14];//14字节的协议地址,包括IP地址和端口
};
  • sa family: address type socket protocol family.
  • sa_data: protocol specific address, different address configuration corresponding to a group of protocols.

Common protocol corresponding value sa_family

Optional value Explanation
AF_INET IPv4 protocol
AF_INET6 IPv6 protocol
AF_LOCAL UNIX agreement
AF_LINK Link protocol address
AF_KEY Key Sockets

Sockaddr addition, the Linux also netinet / in.h defines the sockaddr_in another type of structure, and which can be interchangeable and equivalent sockaddr usually used in programming the protocol relates to TCP / IP's.

struct sockaddr_in
{
    int sa_len;//长度单位
    short int sa_family;//地址族
    unsigned short int sin_port;//端口号
    struct in_addr sin_addr;//IP地址
    unsigned char sin_zero[8];//填充0以保持与struct sockaddr同样大小
};
  • sa_len: unit of length, need not be provided, usually a fixed length of 16 bytes.
  • sa_family: protocol suite.
  • sin_port: port number.
  • sin_addr: IP address, which is itself a structure, the structure is described as follows.
struct sin_addr
{
    in addr_t s_add; //32位IPv4地址,网络字节顺序
};
  • sin_zero: 0 filled, so as to retain the same size and configuration sockaddr structure, to facilitate the conversion.

Note the following when using the structure sockaddr _in:

  • Sockadd_in structure of TCP or UDP port number and IP address sin_port sin_addr are stored in network byte order.
  • 32-bit IP address using two different methods can be cited, for example, consider the definition of the variable as sevaddr Internet socket address structure, it may be used to reference the servaddr.sin_addr.s_addr servaddr.sin_addr or IP address should be noted the former is a reference configuration type (struct sin_addr) data, the latter type of data is an integer of reference; and when the IP address as an argument, what type of data requires explicit use, because the compiler structure type treatment parameters and the integer parameter type is not the same.
  • sin_zero members not used, it is common to and socket address (struct sockaddr) consistent introduced, usually filled with zeros.
  • Socket address structure only native TCP socket protocol record information with this structure variable transmission is not on the network itself, but some of its contents, such as IP addresses and port numbers are transmitted on the network, thus The two parts must be converted to data network byte order.
Published 70 original articles · won praise 131 · views 20000 +

Guess you like

Origin blog.csdn.net/qq_43239560/article/details/102937517