I'm writing a server in C++ using Boost ASIO library. I'd like to get the string representation of client IP to be shown in my server's logs. Does anyone know how to do it?
我正在使用Boost ASIO库用c++编写一个服务器。我希望在服务器的日志中显示客户机IP的字符串表示形式。有人知道怎么做吗?
2 个解决方案
#1
68
The socket has a function that will retrieve the remote endpoint. I'd give this (long-ish) chain of commands a go, they should retrieve the string representation of the remote end IP address:
套接字具有检索远程端点的函数。我给这个(长)命令链一个尝试,他们应该检索字符串表示的远程端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();
or the one-liner version:
或一行程序版本:
asio::ip::tcp::socket socket(io_service);
// Do all your accepting and other stuff here.
std::string s = socket.remote_endpoint().address().to_string();
#2
21
Or, even easier, with boost::lexical_cast
:
或者,更简单,有boost::lexical_cast:
#include <boost/lexical_cast.hpp>
std::string s = boost::lexical_cast<std::string>(socket.remote_endpoint());
#1
68
The socket has a function that will retrieve the remote endpoint. I'd give this (long-ish) chain of commands a go, they should retrieve the string representation of the remote end IP address:
套接字具有检索远程端点的函数。我给这个(长)命令链一个尝试,他们应该检索字符串表示的远程端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();
or the one-liner version:
或一行程序版本:
asio::ip::tcp::socket socket(io_service);
// Do all your accepting and other stuff here.
std::string s = socket.remote_endpoint().address().to_string();
#2
21
Or, even easier, with boost::lexical_cast
:
或者,更简单,有boost::lexical_cast:
#include <boost/lexical_cast.hpp>
std::string s = boost::lexical_cast<std::string>(socket.remote_endpoint());