将IPv4应用程序移植到Dualstack IPv4/IPv6 [英] Porting IPv4 Application to Dualstack IPv4/IPv6

查看:87
本文介绍了将IPv4应用程序移植到Dualstack IPv4/IPv6的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实际上,我正在将IPv4服务器应用程序移植到Linux上的双栈IPv4/IPv6应用程序中.

Actually I'm porting an IPv4 server application to a dualstack IPv4/IPv6 application on Linux.

我使用以下方法解决的基本功能:

The basic function I have solved by using:

serv_addr.sin6_family = AF_INET6;
serv_addr.sin6_addr = in6addr_any;
...
bind(sock, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
...
listen(sock, 5);
...
newsock = accept(syn->sock, (struct sockaddr *) &cli_addr, &clilen);

我可以使用IPv4和IPv6连接并使用连接.但是当我想通过以下方式获取IP时:

I can connect with IPv4 and IPv6 and use the connections. But when I want to get the IP with:

switch(data->sa_family) {
   case AF_INET:
   inet_ntop(AF_INET, &(((struct sockaddr_in*)data)->sin_addr), buffer, size);
   break;
   case AF_INET6:
   inet_ntop(AF_INET6, &(((struct sockaddr_in6*)data)->sin6_addr), buffer, size);
   break;

   default:
   buffer[0] = '?';
   buffer[1] = 0;
}

我总是得到预期的IPv6地址,或者如果它是IPv4连接,例如:: ffff:127.0.0.1

I always get an IPv6 address as expected, or if it is a IPv4 connection something like ::ffff:127.0.0.1

要以127.0.0.1的形式显示为普通的旧IPv4地址(不带:: ffff:-prefix),我需要更改什么?

What do I have to change, to display as a plain old IPv4 address in the form of 127.0.0.1 (without the ::ffff:-prefix)?

谢谢 泰迪

推荐答案

您可以使用2种方法:

  1. 只需从开头就删除该::ffff:(如果存在),并将其作为IPv4的指示.

  1. Just strip off this ::ffff: from the beginning, if present, and take it as indicator for IPv4.

使用两个不同的套接字.周围的操作系统不支持通过一个套接字的IPv4和6(IOW,它们始终启用V6ONLY).尤其是WinXP就是这样做的.

Use two distinct sockets. There are OS around there which do not support IPv4 and 6 via one socket (IOW, they have V6ONLY always enabled). Especially, WinXP does so.

那么您只能做一件事:

  • getaddrinfo()AI_PRIVATE结合使用以获取您可以拥有的所有本地套接字地址
  • 全部使用它们创建一个监听套接字,并在可能的情况下立即启用V6ONLY
  • 将它们的描述符保留在数组中,并使用select()等确定要调用其中的哪个accept().
  • Use getaddrinfo() with AI_PRIVATE for getting all local socket addresses you can have
  • Use them all to create a listening socket and enable V6ONLY immediately, if possible
  • Keep their descriptors in an array and use select() et al to determine which of them to call accept().

听起来比实际要复杂...

Sounds more complicated than it really is...

这篇关于将IPv4应用程序移植到Dualstack IPv4/IPv6的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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