在man unix(7)我发现了以下内容:
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
struct sockaddr_un
定义为
struct sockaddr_un {
sa_family_t sun_family; /* AF_UNIX */
char sun_path[108]; /* pathname */
};
所以我猜我们可以简单地执行 strlen(sun_path) + sizeof(sun_family)
我不明白他们添加的 +1
。你能解释一下吗?我理解 offsetof
用于描述的可移植性
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.
但是这个+1
我不清楚。
最佳答案
How to count the size of the structure?
结构的大小是sizeof(struct sockaddr_un)
。
I don't understand the +1 they added. Can you please give an explanation?
这里的代码试图确定结构中使用(或将要使用)的数据的长度。
offsetof(struct sockaddr_un, sun_path) + strlen(sun_path) + 1
offsetof(struct sockaddr_un, sun_path)
这是直到但不包括.sun_path
成员的偏移量。这是对先前成员和先前填充的数据需求的更糟糕的计算。strlen(sun_path)
是 string 的长度.sun_path[]
中没有空字符。如果sun_path
不包含空字符,结果是未定义的行为 (UB)。+1
用于sun_path
中假定的空字符。
这样的计算对于将struct sockaddr_un
中的数据 发送到某个地方很有用,因为数据 需求可能比 少得多结构需要。
I would guess that we can simply do
strlen(sun_path)
+sizeof(sun_family)
这是一个问题(取决于使用情况)因为
1) 不包含空字符。
2) 它不考虑成员 .sun_family
和 .sun_path
之间的潜在填充。尽管在这种情况下我会很惊讶地看到任何东西。
关于c - 如何计算结构的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53664244/