Boost logo

Boost Users :

Subject: Re: [Boost-users] how to know my own IP address
From: Björn Karlsson (Bjorn.Karlsson_at_[hidden])
Date: 2009-08-14 13:03:55


Hello Paolo,

> I'm using the boost library to create and manage a UDP socket.
> I was wondering if there is a way to know the public address of my
> machine using the boost classes.

Using a resolver to retrieve the address from the host name seems to do the trick:

#include <iostream>
#include <boost/asio.hpp>

int main(int argc, char** argv)
{
  boost::asio::io_service io_service;

  boost::asio::ip::tcp::resolver resolver(io_service);
  boost::asio::ip::tcp::resolver::query query(boost::asio::ip::host_name(), "");
  boost::asio::ip::tcp::resolver::iterator it = resolver.resolve(query);
  boost::asio::ip::tcp::endpoint endpoint = *it;

  std::cout << endpoint.address().to_string() << '\n';

  return 0;
}

Cheers,
Bjorn Karlsson
www.skeletonsoftware.net


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net