【发布时间】:2010-10-10 17:56:39
【问题描述】:
我正在使用 Boost ASIO 库用 C++ 编写服务器。我想让客户端 IP 的字符串表示形式显示在我的服务器日志中。有人知道怎么做吗?
【问题讨论】:
标签: c++ networking boost boost-asio
我正在使用 Boost ASIO 库用 C++ 编写服务器。我想让客户端 IP 的字符串表示形式显示在我的服务器日志中。有人知道怎么做吗?
【问题讨论】:
标签: c++ networking boost boost-asio
套接字具有检索远程端点的功能。我会试一试这个(很长的)命令链,它们应该检索远程端 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();
【讨论】:
或者,更简单的是boost::lexical_cast:
#include <boost/lexical_cast.hpp>
std::string s = boost::lexical_cast<std::string>(socket.remote_endpoint());
【讨论】:
address() 和port(),address().to_string() 省略了。