Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ socket: size of the structure addrinfo

Tags:

c++

sockets

I am using eclipse with cygwin. The application is 64bit. In cygwin the structure is defined as :

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 */
};

The sizeof(addrinfo) result is 48. The size of socketlen_t is 4 bytes. The int type size is 4 bytes. The pointer is 8 bytes in the 64 bits application. The total bytes is 44(4 ints = 16 bytes, socket_len = 4 bytes, 3 pointers = 24; 20+4+24 = 44). I am wondering what the missing 4 bytes for? Are they for padding? I thought 44 bytes do not need to be aligned. Any thought?

Thanks for the answer in advance.

like image 693
r0n9 Avatar asked Feb 13 '16 22:02

r0n9


2 Answers

It's padding, after the socklen_t. The next variable in the struct is a pointer, which is 64-bits in length, and will (in this case) be aligned to 64-bits as well. Note however that padding is dependent on architecture and compiler settings; it happens here, but is not guaranteed to always happen.

Note that since you are sharing this struct with the operating system, you should NOT try to change the padding yourself (most compilers allow this using compiler switches and/or pragmas). The OS is expecting this struct with a certain amount of padding included. If you fail to provide it, all the pointers at the end of the struct will have their values misinterpreted.

like image 67
H. Guijt Avatar answered Nov 22 '22 14:11

H. Guijt


It's "struct member alignment", the /Zp flag
Data structure alignment,
Microsoft documentation

like image 24
Tom Chadaravicius Avatar answered Nov 22 '22 13:11

Tom Chadaravicius