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

kyk*_*yku 56 c++ networking boost boost-asio

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

pax*_*blo 76

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

或单行版本:

asio::ip::tcp::socket socket(io_service);
// Do all your accepting and other stuff here.

std::string s = socket.remote_endpoint().address().to_string();
Run Code Online (Sandbox Code Playgroud)

  • 是的,我就是这样做的(假设在临时点没有空值或错误的可能性).为了解释的目的,我把它扩展了.在我看来,单行版本更好(我喜欢我的代码相对紧凑,所以我可以在屏幕上看到更多). (3认同)

mar*_*n78 23

或者,更简单,有boost::lexical_cast:

#include <boost/lexical_cast.hpp>

std::string s = boost::lexical_cast<std::string>(socket.remote_endpoint());
Run Code Online (Sandbox Code Playgroud)

  • 这非常有用,因为它同时包含了 `address()` 和 `port()`,而 `address().to_string()` 忽略了它们。 (2认同)