如何同时支持 IPv4 和 IPv6 连接

2023-01-19C/C++开发问题
21

本文介绍了如何同时支持 IPv4 和 IPv6 连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我目前正在开发一个 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 连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6