66

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

4

2 回答 2

92

套接字具有检索远程端点的功能。我会试一试这个(长的)命令链,它们应该检索远程端 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();
于 2009-03-02T10:05:17.787 回答
26

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

#include <boost/lexical_cast.hpp>

std::string s = boost::lexical_cast<std::string>(socket.remote_endpoint());
于 2012-09-05T15:10:55.080 回答