Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 879
kyku Avatar asked Mar 02 '09 09:03

kyku


People also ask

How do I find my local IP address C++?

You can use gethostname followed by gethostbyname to get your local interface internal IP.

What is ASIO boost?

Boost. Asio is a cross-platform C++ library for network and low-level I/O programming that provides developers with a consistent asynchronous model using a modern C++ approach. Overview.


2 Answers

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();
like image 100
paxdiablo Avatar answered Oct 21 '22 07:10

paxdiablo


Or, even easier, with boost::lexical_cast:

#include <boost/lexical_cast.hpp>

std::string s = boost::lexical_cast<std::string>(socket.remote_endpoint());
like image 26
marton78 Avatar answered Oct 21 '22 08:10

marton78