Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top