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

有帮助吗?

解决方案

套接字具有检索远程端点的功能。我给这个(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();

其他提示

或者,更简单,使用 boost :: lexical_cast

#include <boost/lexical_cast.hpp>

std::string s = boost::lexical_cast<std::string>(socket.remote_endpoint());
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top