Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Point of passing address and size in functions

Tags:

c++

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?

like image 482
Sway Avatar asked Dec 06 '15 13:12

Sway


2 Answers

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.

like image 125
ivan.ukr Avatar answered Oct 07 '22 07:10

ivan.ukr


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.

like image 25
Alan Stokes Avatar answered Oct 07 '22 09:10

Alan Stokes