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

67

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

2个回答

97

这个套接字有一个函数可以获取远程端点。你可以尝试以下这个(有些长)命令链,它们应该可以检索远程端点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();

谢谢你的回答,我发现这个链可以简单地写成: socket.remote_endpoint().address().to_string() - kyku
3
是的,这就是我所做的方式(假设中间点没有空值或错误)。我扩展了代码以解释说明。在我看来,单行版本更好(我喜欢紧凑的代码,这样我可以在屏幕上看到更多内容)。 - paxdiablo

26

或者更简单的方式,使用 boost::lexical_cast

#include <boost/lexical_cast.hpp>

std::string s = boost::lexical_cast<std::string>(socket.remote_endpoint());

2
这很有用,因为它包括 address()port(),而 address().to_string() 则不包括端口。 - Sean
1
请注意,如果端点未连接,则会引发异常。 - Claudiu
我可以通过本地连接方式获取IP地址吗? - Viktor Sehr

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接