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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/601763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 16:11:46  来源:igfitidea点击:

How to get IP address of boost::asio::ip::tcp::socket?

c++networkingboostboost-asio

提问by kyku

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 的字符串表示。有谁知道怎么做?

回答by paxdiablo

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

回答by marton78

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