简体   繁体   English

如何使用recvfrom获取AF_INET6套接字的地址

[英]How to get an addres of AF_INET6 socket with recvfrom

recvfrom requires the 5-th parameter to be a pointer to sockaddr structure and the 6-th parameter to be a pointer to a socklen_t . recvfrom要求第5个参数是指向sockaddr结构的指针,第6个参数是指向socklen_t的指针。

man recvfrom (3) says: man recvfrom (3)说:

If the actual length of the address is greater than the length of the supplied sockaddr structure, the stored address shall be truncated. 如果地址的实际长度大于提供的sockaddr结构的长度,则应截断存储的地址。

I don't get it how can I retrieve an address of a sending socket with AF_INET6 address family since the size of sockaddr_in6 is greater than sockaddr thus it would be truncated by recvfrom . 我不知道如何检索具有AF_INET6地址族的发送套接字的地址,因为sockaddr_in6的大小大于sockaddr因此它将被recvfrom截断。

Do I get it right that recvfrom can not retrieve addresses larger than sizeof(sockaddr) ? 我是否认为recvfrom无法检索大于sizeof(sockaddr)地址?

Do I get it right that even if I define an instance of sockaddr_in6 cast it's address to sockaddr* and pass it to recvfrom , the function would not be able to know that enough space is available to store the address? 我是否正确,即使我定义sockaddr_in6的实例将其地址转换为sockaddr*并将其传递给recvfrom ,该函数也无法知道有足够的空间可用于存储地址?

You pass the pointer of the sockaddr_in6 (type-casted) and the size of the sockaddr_in6 structure as arguments: 您将sockaddr_in6 (type-casted)的指针和sockaddr_in6结构的大小作为参数传递:

struct sockaddr_in6 in6;
socklen_t len6 = sizeof(in6);

recvfrom(sock, buf, buflen, (struct sockaddr *) &in6, &len6);

Since you pass in the correct length to the function, it will work. 由于您将正确的长度传递给函数,因此它将起作用。

It's correct to cast it to sockaddr* . 将它投射到sockaddr*是正确的。

Further more, people use often sockaddr_storage , because it is defined as 此外,人们经常使用sockaddr_storage ,因为它被定义

The header shall define the sockaddr_storage structure. 标题应定义sockaddr_storage结构。 This structure shall be: 该结构应为:

  • Large enough to accommodate all supported protocol-specific address structures 足够大以容纳所有支持的协议特定的地址结构
  • Aligned at an appropriate boundary so that pointers to it can be cast as pointers to protocol-specific address structures and used to access the fields of those structures without alignment problems 在适当的边界对齐,以便指向它的指针可以作为指向协议特定地址结构的指针,并用于访问这些结构的字段而没有对齐问题

In this way you can use it for several protocols, so you're not boundedn to only IPv6 or IPv4. 通过这种方式,您可以将它用于多种协议,因此您不会受到IPv6或IPv4的限制。

So you can do 所以你可以做到

struct sockaddr_storage addr;
socklen_t sa_len = sizeof(addr);

recvfrom (sock, buffer, sizeof (buffer), (struct sockaddr*) &addr, &sa_len);

If you need to know what kinf of sockaddr is, you can check the mandatory sa_family_t ss_family field present in each sockaddr struct. 如果你需要知道sockaddr的kinf是什么,你可以检查每个sockaddr结构中存在的强制sa_family_t ss_family字段。

You may also be interested in this link or this one . 您还可能有兴趣在此链接或此一个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM