gpt4 book ai didi

c - 为什么 sockaddr_in 中需要零填充?

转载 作者:IT王子 更新时间:2023-10-29 00:27:39 26 4
gpt4 key购买 nike

我在谷歌上搜索了一下,有人说“为了与 struct sockaddr 保持相同的大小”。但是内核不会直接使用 sockaddr(对吧?)。使用时。内核会将其转换回原来的样子。那么为什么需要零填充?

struct sockaddr {
unsigned short sa_family; // address family, AF_xxx
char sa_data[14]; // 14 bytes of protocol address
};

struct sockaddr_in {
short sin_family; // e.g. AF_INET, AF_INET6
unsigned short sin_port; // e.g. htons(3490)
struct in_addr sin_addr; // see struct in_addr, below
char sin_zero[8]; // zero this if you want to
};

struct in_addr {
unsigned long s_addr; // load with inet_pton()
};

最佳答案

我能找到的两条更相关的信息是

谈论清除字节的代码片段

This is a bug. I see it occur occasionaly. This bug can cause undefined behaviour in applications.

后面有一些解释

Most of the net code does not use sockaddr_in, it uses sockaddr. When you use a function like sendto, you must explicitly cast sockaddr_in, or whatever address you are using, to sockaddr. sockaddr_in is the same size as sockaddr, but internally the sizes are the same because of a slight hack.

That hack is sin_zero. Really the length of useful data in sockaddr_in is shorter than sockaddr. But the difference is padded in sockaddr_in using a small buffer; that buffer is sin_zero.

最后,一个可以在不同地方找到的信息

On some architectures, it wont cause any problems not clearing sin_zero. But on other architectures it might. Its required by specification to clear sin_zero, so you must do this if you intend your code to be bug free for now and in the future.

回答问题

why we need this 8 byte padding?

和答案

Unix network programming chapter 3.2 says that, "The POSIX specification requires only three members in the structure: sin_family, sin_addr, and sin_port. It is acceptable for a POSIX-compliant implementation to define additional structure members, and this is normal for an Internet socket address structure. Almost all implementations add the sin_zero member so that all socket address structures are at least 16 bytes in size. "

It's kinda like structure padding, maybe reserved for extra fields in the future. You will never use it, just as commented.

与第一个链接一致。清除字节会告诉接收方“这些字节未在我们这边使用”。

关于c - 为什么 sockaddr_in 中需要零填充?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15608707/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com