如何获取 boost::asio::ip::tcp::socket 的 IP 地址?

2021-12-20 00:00:00 networking c++ boost boost-asio

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

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?

推荐答案

socket 有一个函数可以检索远程端点.我会尝试一下这个(长的)命令链,它们应该检索远程端 IP 地址的字符串表示:

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:

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();

相关文章