Reputation: 9521
In the man unix(7) I found the following:
pathname: a UNIX domain socket can be bound to a null-terminated filesystem pathname using bind(2). When the address of a pathname socket is returned (by one of the system calls noted above), its length is
offsetof(struct sockaddr_un, sun_path) + strlen(sun_path) + 1
The struct sockaddr_un
is defined as
struct sockaddr_un {
sa_family_t sun_family; /* AF_UNIX */
char sun_path[108]; /* pathname */
};
So I would guess that we can simply do strlen(sun_path) + sizeof(sun_family)
I don't understand the +1
they added. Can you please give an explanation? I understand the offsetof
uses for portabiliy as described
On Linux, the above
offsetof()
expression equates to the same value assizeof(sa_family_t)
, but some other implementations include other fields before sun_path, so theoffsetof()
expression more portably describes the size of the address structure.
But this +1
is not clear to me.
Upvotes: 3
Views: 162
Reputation: 153338
How to count the size of the structure?
The size of the structure is sizeof(struct sockaddr_un)
.
I don't understand the +1 they added. Can you please give an explanation?
Here the code is trying to determine the length of the data used (or to be used) in the structure.
offsetof(struct sockaddr_un, sun_path) + strlen(sun_path) + 1
offsetof(struct sockaddr_un, sun_path)
This is the offset up to, but not including, the .sun_path
member. It is a worse cast calculation of the data needs of prior members and prior padding.
strlen(sun_path)
is the length of the string without the null character in .sun_path[]
. Should sun_path
not include a null character, the result is undefined behavior (UB).
+1
is for the assumed null character in sun_path
.
Such a calculation is useful to send the data in struct sockaddr_un
someplace as the data needs may be significantly less than the structure needs.
I would guess that we can simply do
strlen(sun_path)
+sizeof(sun_family)
This is a problem (depending on usage) because
1) It does not include the null character.
2) It does not account for potential padding between members .sun_family
and .sun_path
. Although in this case I would be surprised to see any.
Upvotes: 3