为什么我们可以将sockaddr转换为sockaddr_in [英] Why can we cast sockaddr to sockaddr_in

查看:85
本文介绍了为什么我们可以将sockaddr转换为sockaddr_in的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以看到将 sockaddr 强制转换为 sockaddr_in 的原因,但是我不知道这是怎么可能的.根据我的阅读,它们的大小相同,并且 sockaddr_in sin_zero 添加在一起以使其具有相同的大小.我想知道编译器如何知道从 sockaddr_in 那里获取信息的方式,如果它的布局与 sockaddr 不同.

I can see why it is useful to cast sockaddr to sockaddr_in, but I don't understand how this is possible. From what I've read, they're the same size and sockaddr_in is added with sin_zero to make it the same size. 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.

推荐答案

之所以可能,是因为通常投射指针,而不是结构本身.您执行自然语言的意思是请将该指向 socket结构的指针视为指向 internet套接字结构的指针".编译器没有任何问题可以重新解释指针.

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". Compiler has no problems to re-interpret the pointer.

这里是从评论中提取的更详细的描述:

Here is more detailed description taken up from comments:

sockaddr 的大小为16个字节-前两个字节为 sa_family ,其余的14个字节为 sa_data 任意数据. sockaddr_in 的大小也为16个字节-前2个字节为 sin_family (始终为 AF_INET ),接下来的2个字节为 sin_port ,后4个字节是 sin_addr (IP地址),后8个字节是 sin_zero ,在IPv4中未使用,仅提供给确保16个字节.这样,您可以先查看 sockaddr.sa_family ,如果它是 AF_INET ,然后将整个 sockaddr 解释为 sockaddr_in .

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. 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. 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_in 未存储在 sockaddr.sa_data 字段内.整个 sockaddr 是整个 sockaddr_in (也就是说,当 sockaddr.sa_family AF_INET 时).如果采用 sockaddr * 指针并将其强制转换为 sockaddr_in * 指针,则:

A sockaddr_in is not stored inside of sockaddr.sa_data field. The entire sockaddr is the entire sockaddr_in (when sockaddr.sa_family is AF_INET, that is). If you take a sockaddr* pointer and cast it to a sockaddr_in* pointer, then:

  • sockaddr.sa_family sockaddr_in.sin_family
  • sockaddr.sa_data
  • 字节0-1是 sockaddr_in.sin_port
  • 第2-5个字节是 sockaddr_in.sin_addr
  • 字节6-13是 sockaddr_in.sin_zero .
  • sockaddr.sa_family is sockaddr_in.sin_family
  • bytes 0-1 of sockaddr.sa_data are sockaddr_in.sin_port
  • bytes 2-5 are sockaddr_in.sin_addr
  • bytes 6-13 are sockaddr_in.sin_zero.

这篇关于为什么我们可以将sockaddr转换为sockaddr_in的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆