【问题标题】:Find server IP using Boost Asio使用 Boost Asio 查找服务器 IP
【发布时间】:2017-04-18 08:24:04
【问题描述】:

我正在使用 Boost ASIO 库用 C++ 编写客户端。我想在我的客户端日志中显示服务器 IP 的字符串表示形式。有人知道怎么做吗?

【问题讨论】:

  • 感谢使用 boost asio 对“网络状态”的任何提示。
  • 识别和报告“网络状态”对我来说似乎是一个完全不同的问题。
  • 这仍然是一个悬而未决的问题。 @moooeeeep
  • 一般的经验法则是:每个帖子一个问题。
  • 我会为它打开一个单独的线程。 @moooeeeep

标签: c++ boost-asio


【解决方案1】:

就获取 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 中从未见过这样的功能。

【讨论】:

  • 我也在寻求帮助。
【解决方案2】:
std::string s = boost::lexical_cast<std::string>(socket.remote_endpoint());

这应该可以解决问题!

【讨论】:

    【解决方案3】:

    您可能正在寻找主机查找:

    #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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多