使用Boost ASIO查找服务器IP

Find server IP using Boost Asio

本文关键字:服务器 IP 查找 ASIO Boost 使用      更新时间:2023-10-16

我正在使用boost asio库在C 上编写客户端。我想获取服务器IP的字符串表示形式,以显示在我的客户端日志中。有人知道该怎么做吗?

就获得IP而言,插座具有将检索远程端点的函数。我会提供这条命令链,他们应该检索远程终端IP地址的字符串表示:

asio::ip::tcp::socket socket(io_service);
// Do all your accepting and other stuff here.
asio::ip::tcp::endpoint remote_ep = socket.remote_endpoint();
asio::ip::address remote_ad = remote_ep.address();
std::string s = remote_ad.to_string();

对于连接性的角度,从未在ASIO中看到过这样的功能。

std::string s = boost::lexical_cast<std::string>(socket.remote_endpoint());

这应该可以解决问题!

您可能想做主机查找:

#include <iostream>
#include <boost/asio.hpp>
#include <boost/range/iterator_range.hpp>
using boost::asio::ip::tcp;
int main() {
    char name[64], domain[64];
    if (::gethostname(name, 64))     ::perror("gethostname failed");
    if (::getdomainname(domain, 64)) ::perror("getdomainname failed");
    boost::asio::io_service ios;
    tcp::resolver res(ios);
    std::string name_s(name), domain_s(domain);
    for (auto match : boost::make_iterator_range(res.resolve({name_s+"."+domain_s, "0"}), {})) {
        std::cout << name << " -> " << match.endpoint().address() << "n";
    }
}

可能会打印

之类的东西
desktop.fritz.box -> 192.168.182.20