【问题标题】:How to get IP address of boost::asio::ip::tcp::socket?如何获取 boost::asio::ip::tcp::socket 的 IP 地址?
【发布时间】:2010-10-10 17:56:39
【问题描述】:

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

【问题讨论】:

    标签: c++ networking boost boost-asio


    【解决方案1】:

    套接字具有检索远程端点的功能。我会试一试这个(很长的)命令链,它们应该检索远程端 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::ip::tcp::socket socket(io_service);
    // Do all your accepting and other stuff here.
    
    std::string s = socket.remote_endpoint().address().to_string();
    

    【讨论】:

    • 感谢您的回答,我发现链可以简单地写成:socket.remote_endpoint().address().to_string()
    • 是的,我就是这样做的(假设在中间点没有空值或错误的可能性)。出于解释的目的,我将其扩展。在我看来,单行版本更好(我喜欢我的代码相对紧凑,因此我可以在屏幕上看到更多内容)。
    【解决方案2】:

    或者,更简单的是boost::lexical_cast

    #include <boost/lexical_cast.hpp>
    
    std::string s = boost::lexical_cast<std::string>(socket.remote_endpoint());
    

    【讨论】:

    • 这非常有用,因为它包括address()port()address().to_string() 省略了。
    • 请注意,如果端点未连接,则会引发异常。
    • 我可以通过某种方式在本地连接它以获得 ip 吗?
    猜你喜欢
    • 1970-01-01
    • 2018-06-08
    • 2011-10-14
    • 1970-01-01
    • 1970-01-01
    • 2012-06-26
    • 2015-01-13
    • 2017-04-27
    相关资源
    最近更新 更多