Reputation: 28545
In socket programming, especially while dealing with Unix domain sockets of type struct sockaddr_un
, some people use offsetof()
to calculate the size of the sockaddr_un
structure like-
struct sockaddr_un {
sa_family_t sun_family; /* AF_UNIX */
char sun_path[108]; /* pathname */
};
size = (offsetof (struct sockaddr_un, sun_path)
+ strlen (name.sun_path));
In some other places, they use
size = sizeof(struct sockaddr_un)
I understand that the first method accounts for shorter path names and the second gives a fixed max size irrespective of the actual path length.
Does it really make a difference to a function like bind
which is passed this value? If not, can these 2 be used interchangeably?
Upvotes: 3
Views: 364
Reputation: 310985
I would say the offsetof
version you posted is incorrect. It should have at least a +1 in it, as the path is defined as a null-terminated string, and that's the length that the kernel returns e.g. from getsockname()
.
Even with the +1, I don't see the point of using something complex over something simple. It does save a few bytes being transferred to the kernel, but bind()
and friends are hardly the rate-determine steps.
Upvotes: 0
Reputation: 2606
offsetof takes into account any padding that the C compiler may have added after the size of the base members. However, if you define network packets using C structures that contain padding added by the C compiler, you have bigger problems! In fact I'd ensure that a test case was added which ensures that both methods return the same size, to guard against incorrect compile options changing padding rules, for example.
In the context of this question, no, it doesn't make any difference to bind.
Upvotes: 2