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

C++NetworkingBoostBoost Asio

C++ Problem Overview


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?

C++ Solutions


Solution 1 - C++

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

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

Solution 2 - C++

Or, even easier, with boost::lexical_cast:

#include <boost/lexical_cast.hpp>

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkykuView Question on Stackoverflow
Solution 1 - C++paxdiabloView Answer on Stackoverflow
Solution 2 - C++marton78View Answer on Stackoverflow