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

38,323

Solution 1

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

Or, even easier, with boost::lexical_cast:

#include <boost/lexical_cast.hpp>

std::string s = boost::lexical_cast<std::string>(socket.remote_endpoint());
Share:
38,323
kyku
Author by

kyku

A programmer...

Updated on July 29, 2020

Comments

  • kyku
    kyku almost 4 years

    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?

  • kyku
    kyku about 15 years
    Thanks for your answer, I figured out the chain can be written simply as: socket.remote_endpoint().address().to_string()
  • paxdiablo
    paxdiablo about 15 years
    Yeah, that's how I would have done it (assuming there was no possibilities of nulls or errors at interim points). I left it expanded for explanatory purposes. In my opinion, the one-liner version is better (I like my code relatively compact so I can see more of it on a screen).
  • Sean
    Sean about 11 years
    This is very useful because it includes both the address() and port(), which address().to_string() leaves out.
  • Claudiu
    Claudiu over 9 years
    Note that this throws an exception if the endpoint is not connected.
  • Viktor Sehr
    Viktor Sehr almost 4 years
    Can I connect it locally somehow just to get the ip?