I am doing socket programming in C++ and i see a lot of functions that take structure pointers as well as sizes. For instance,
struct sockaddr dest;
//fill dest
sendto(dgram_socket, secret_message, len, 0, &dest, sizeof dest);
Whats the point of passing size of a fixed length structure (sockaddr) when the function can clearly interpret it from the type?
Because actually sockaddr is only placeholder data type here. The actual data structure that you pass may differ. For example, address structures for IPv4 and IPv6 differ in content and length. And that's the point of passing structure size.
In general, this is widely used technique. Either size is passed as additioanl parameter or size member is included directly to the structure (typically, as its very first member). This allows the receiving function to distinguish between different known versions of that structure, in the situations, when API changes over the time and new members are added, but still programs alrady compiled with older API defintions have passing strutures with actual size less than it is in the most recent one. This is typical technique faced in the Windows API - many Windows native structures have something like DWORD cbSize
in them.
The sockaddr
structure is not actually fixed in size - different types of socket need different sizes of address information (e.g. IPv4 or IPv6).
So in this particular case it is actually useful and necessary to specify the length of the actual sockaddr
that you have.
See for example http://pubs.opengroup.org/onlinepubs/009695399/basedefs/sys/socket.h.html.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With