0

I have this code in my server (scattered around the constructors etc. but I've left out the unnecessary parts):

using namespace boost::asio;
io_service ioserv;
ip::tcp::endpoint endpoint(ip::tcp::v4(), 1922);
ip::tcp::acceptor acceptor(ioserv, endpoint);
ip::tcp::socket socket(ioserv);
acceptor.accept(socket);

Now I want to write my IP to the console. Unfortunately both

cout << endpoint.address() << endl;

and

cout << acceptor.local_endpoint().address() << endl;

print

0.0.0.0

How to get the IP address of my machine?

marczellm
  • 1,224
  • 2
  • 18
  • 42

2 Answers2

3

Where did you get that code?

Try this:

#include <boost/asio.hpp>
using boost::asio::ip::tcp;    

boost::asio::io_service io_service;
tcp::resolver resolver(io_service);
tcp::resolver::query query(boost::asio::ip::host_name(), "");
tcp::resolver::iterator iter = resolver.resolve(query);
tcp::resolver::iterator end; // End marker.
while (iter != end)
{
    tcp::endpoint ep = *iter++;
    std::cout << ep << std::endl;
}

And take a look at this discussion.

Community
  • 1
  • 1
Luca Davanzo
  • 21,000
  • 15
  • 120
  • 146
  • Answering your question: As I said, I've left out the unnecessary parts. The acceptor is there because the server accepts connections. For simplicity, I've only included one such accept. Is there anything wrong with my code? – marczellm Dec 14 '13 at 11:30
3

The default bind-address is INADDR_ANY, which is 0.0.0.0, which means that the socket will accept connections via any interface. Your code is perfectly correct, except that it isn't a correct way to ascertain your IP address. You can get that directly via the Sockets API without creating a socket at all.

user207421
  • 305,947
  • 44
  • 307
  • 483