c-来自任何有效地址的ipv4和ipv6
作者:互联网
我正在尝试从任何字符串地址获取ipv4和ipv6地址,无论是通过ipv4,ipv6还是DNS地址.
我可以创建自己的函数来执行此操作,但是我尝试使用expert advice并利用内置功能.
有没有办法输入任何格式的地址字符串,并同时返回ipv4和ipv6提升地址?
解决方法:
从DNS名称获取地址涉及…查询命名服务器(DNS!).如果要枚举结果,请在asio中使用解析器:
> http://www.boost.org/doc/libs/1_55_0/doc/html/boost_asio/reference/ip__tcp/resolver.html
简单的例子:
#include <boost/asio.hpp>
#include <boost/function_output_iterator.hpp>
#include <set>
using boost::asio::ip::address;
std::set<address> unique_endpoints(std::string const& ip)
{
using resolver = boost::asio::ip::tcp::resolver;
boost::asio::io_service ios; // TODO use existing service / resolver
resolver r(ios);
std::set<address> unique;
for (auto it = r.resolve({ip, ""}); it != resolver::iterator {}; ++it)
{
//std::cout << "Resolved: " << it->host_name() << " -> " << it->endpoint() << " " << it->service_name() << "\n";
address a = it->endpoint().address();
if (a.is_v4())
unique.insert(boost::asio::ip::address_v6::v4_mapped(a.to_v4()));
else
unique.insert(a);
}
return unique;
}
template <typename S>
bool endpoints_overlap(S const& a, S const& b)
{
bool matching_found = false;
std::set_intersection(
a.begin(), a.end(), b.begin(), b.end(),
boost::make_function_output_iterator([&](address const&) { matching_found = true; }));
return matching_found;
}
int main()
{
auto h = unique_endpoints("bbs2.fritz.box");
auto a = unique_endpoints("192.168.2.111");
auto b = unique_endpoints("::ffff:192.168.2.111");
auto c = unique_endpoints("::ffff:c0a8:026f");
assert(endpoints_overlap(a, b));
assert(endpoints_overlap(a, c));
assert(endpoints_overlap(b, c));
assert(endpoints_overlap(h, a));
assert(endpoints_overlap(h, b));
assert(endpoints_overlap(h, c));
}
请注意,当DNS响应之一匹配时,此测试将确定端点重叠.这在群集设置中可能并不总是正确的(?那里没有专家),并且您可能还想在使用此算法之前检测广播地址(未经测试).
另请注意,我认为没有办法检测实际主机的等效性(这意味着,如果主机具有多个物理/逻辑NIC,它们将在传输级别上显示为单独的服务器).
最后,在实际应用程序中,您将需要异步进行解析(使用async_resolve)
标签:boost,boost-asio,ip-address,linux,c-4 来源: https://codeday.me/bug/20191029/1960109.html