c ++ socket:结构addrinfo的大小

r0n*_*0ng 5 c++ sockets

我正在使用eclipse和cygwin.该应用程序是64位.在cygwin中,结构定义为:

struct addrinfo {
  int             ai_flags;         /* input flags */
  int             ai_family;        /* address family of socket */
  int             ai_socktype;      /* socket type */
  int             ai_protocol;      /* ai_protocol */
  socklen_t       ai_addrlen;       /* length of socket address */
  char            *ai_canonname;    /* canonical name of service location */
  struct sockaddr *ai_addr;         /* socket address of socket */
  struct addrinfo *ai_next;         /* pointer to next in list */
};
Run Code Online (Sandbox Code Playgroud)

sizeof(addrinfo)结果为48. socketlen_t的大小为4个字节.int类型大小为4个字节.指针在64位应用程序中是8个字节.总字节数为44(4个字节= 16个字节,socket_len = 4个字节,3个指针= 24; 20 + 4 + 24 = 44).我想知道丢失的4个字节是什么?它们是用于填充吗?我认为44字节不需要对齐.任何想法?

谢谢你提前回答.

H. *_*ijt 4

它是在 socklen_t 之后的填充。结构中的下一个变量是一个指针,其长度为 64 位,并且(在本例中)也将与 64 位对齐。但请注意,填充取决于体系结构和编译器设置;它发生在这里,但不保证总是发生。

请注意,由于您与操作系统共享此结构,因此您不应尝试自己更改填充(大多数编译器允许使用编译器开关和/或编译指示)。操作系统期望该结构包含一定量的填充。如果您未能提供它,则结构末尾的所有指针的值都将被错误解释。