如何获取boost :: asio :: ip :: tcp :: socket的IP地址?

时间:2009-03-02 09:37:10

标签: c++ networking boost boost-asio

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

2 个答案:

答案 0 :(得分:72)

套接字具有检索远程端点的功能。我给这个(long-ish)命令链一个go,他们应该检索远程端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();

答案 1 :(得分:23)

或者,更简单,boost::lexical_cast

#include <boost/lexical_cast.hpp>

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