[英]Why can we cast sockaddr to sockaddr_in
I can see why it is useful to cast sockaddr
to sockaddr_in
, but I don't understand how this is possible. 我可以看出为什么将
sockaddr
为sockaddr_in
是有用的,但我不明白这是怎么回事。 From what I've read, they're the same size and sockaddr_in
is added with sin_zero
to make it the same size. 根据我的阅读,它们的大小相同,
sockaddr_in
与sin_zero
一起添加,使其大小相同。 I would like to know how the compiler knows where to get the information from sockaddr_in
if it is layed out differently to sockaddr
. 我想知道编译器如何知道从哪里得到的信息
sockaddr_in
如果是奠定了不同来sockaddr
。
It is possible because you normally cast pointers, not the structures themselves. 这是可能的,因为你通常会转换指针,而不是结构本身。 You do what in natural language means "please treat this pointer to a
socket structure
as a pointer to an internet socket structure
instead". 你做自然语言什么的意思是“请把这个指针
socket structure
作为一个指针internet socket structure
,而不是”。 Compiler has no problems to re-interpret the pointer. 编译器重新解释指针没有问题。
Here is more detailed description taken up from comments: 以下是评论中更详细的描述:
A sockaddr
is 16 bytes in size - the first two bytes are the sa_family
, and the remaining 14 bytes are the sa_data
which is arbitrary data. sockaddr
大小为16个字节 - 前两个字节是sa_family
,剩下的14个字节是sa_data
,它是任意数据。 A sockaddr_in
is also 16 bytes in size - the first 2 bytes are the sin_family
(always AF_INET
), the next 2 bytes are the sin_port
, the next 4 bytes are the sin_addr
(IP address), and the last 8 bytes are the sin_zero
which is unused in IPv4 and provided only to ensure 16 bytes. sockaddr_in
大小也是16个字节 - 前2个字节是sin_family
(总是AF_INET
),接下来的2个字节是sin_port
,接下来的4个字节是sin_addr
(IP地址),最后8个字节是sin_zero
在IPv4中未使用,仅提供16个字节。 This way, you can look at sockaddr.sa_family
first, and if it is AF_INET
then interpret the entire sockaddr
as a sockaddr_in
. 这样,您可以先查看
sockaddr.sa_family
,如果是AF_INET
则将整个sockaddr
解释为sockaddr_in
。
A sockaddr_in
is not stored inside of sockaddr.sa_data
field. sockaddr_in
不存储在sockaddr.sa_data
字段中。 The entire sockaddr
is the entire sockaddr_in
(when sockaddr.sa_family
is AF_INET
, that is). 整个
sockaddr
是整个sockaddr_in
(当sockaddr.sa_family
是AF_INET
时,就是这样)。 If you take a sockaddr*
pointer and cast it to a sockaddr_in*
pointer, then: 如果你带一个
sockaddr*
指针并将其转换为sockaddr_in*
指针,那么:
sockaddr.sa_family
is sockaddr_in.sin_family
sockaddr.sa_family
是sockaddr_in.sin_family
sockaddr.sa_data
are sockaddr_in.sin_port
sockaddr.sa_data
字节0-1是sockaddr_in.sin_port
sockaddr_in.sin_addr
sockaddr_in.sin_addr
sockaddr_in.sin_zero
. sockaddr_in.sin_zero
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.