问题描述
我目前正在开发一个 UDP 套接字应用程序,我需要构建支持,以便 IPV4 和 IPV6 连接可以将数据包发送到服务器.
I'm currently working on a UDP socket application and I need to build in support so that IPV4 and IPV6 connections can send packets to a server.
我希望有人能帮助我并指出正确的方向;我发现的大部分文档都不完整.如果您能指出 Winsock 和 BSD 套接字之间的任何区别,也会很有帮助.
I was hoping that someone could help me out and point me in the right direction; the majority of the documentation that I found was not complete. It'd also be helpful if you could point out any differences between Winsock and BSD sockets.
提前致谢!
推荐答案
最好的方法是创建一个也可以接受 IPv4 连接的 IPv6 服务器套接字.为此,创建一个常规的 IPv6 套接字,关闭关闭套接字选项IPV6_V6ONLY
,将其绑定到任何"地址,然后开始接收.IPv4 地址将显示为 IPv6 地址,采用 IPv4-mapped 格式.
The best approach is to create an IPv6 server socket that can also accept IPv4 connections. To do so, create a regular IPv6 socket, turn off the socket option IPV6_V6ONLY
, bind it to the "any" address, and start receiving. IPv4 addresses will be presented as IPv6 addresses, in the IPv4-mapped format.
不同系统的主要区别在于 IPV6_V6ONLY
是否 a) 可用,以及 b) 默认打开或关闭.它在 Linux 上默认关闭(即允许没有 setsockopt 的双栈套接字),并在大多数其他系统上打开.
The major difference across systems is whether IPV6_V6ONLY
is a) available, and b) turned on or off by default. It is turned off by default on Linux (i.e. allowing dual-stack sockets without setsockopt), and is turned on on most other systems.
此外,Windows XP 上的 IPv6 堆栈不支持该选项.在这些情况下,您需要创建两个单独的服务器套接字,并将它们放入 select 或多个线程中.
In addition, the IPv6 stack on Windows XP doesn't support that option. In these cases, you will need to create two separate server sockets, and place them into select or into multiple threads.
这篇关于如何同时支持 IPv4 和 IPv6 连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!