我正在使用Boost ASIO库用C++编写服务器。 我希望在我的服务器日志中显示客户端IP的字符串表示。 有人知道如何做吗?
我正在使用Boost ASIO库用C++编写服务器。 我希望在我的服务器日志中显示客户端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::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()
则不包括端口。 - Sean