Point of passage of address and size in functions

I do socket programming in C ++, and I see a lot of functions that take pointers to structure as well as sizes. For instance,

struct sockaddr dest; //fill dest sendto(dgram_socket, secret_message, len, 0, &dest, sizeof dest); 

What is the transmission point of a fixed-length structure size (sockaddr) when a function can clearly interpret it from a type?

+5
source share
2 answers

Because sockaddr is actually just a placeholder data type. The actual data structure you transmit may vary. For example, the address structures for IPv4 and IPv6 differ in content and length. And this is the passing point of the size of the structure.

In general, this is a widely used technique. Any size is passed because the parameter or element of size additioanl is included directly in the structure (as a rule, as its first member). This allows the receiving function to distinguish between different known versions of this structure, in situations where the API changes over time and new members are added, but still alrady programs compiled with older API definitions have a passage with a real size smaller than that in the latest . This is a typical technique found in the Windows API. Many related Windows structures have something like a DWORD cbSize in them.

+4
source

The sockaddr structure is actually not fixed in size - different types of sockets need different sizes of address information (for example, 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 .

+2
source

Source: https://habr.com/ru/post/1237505/


All Articles