boost asio TCP server must bind to an IP address?

6.2k views Asked by At

I am not sure whether I am using BOOST ASIO properly, my code is as follows,

  boost::asio::ip::tcp::resolver resolver(io_);
  boost::asio::ip::tcp::resolver::query query(std::string("127.0.0.1"), port);
  boost::asio::ip::tcp::endpoint endpoint = *resolver.resolve(query);
  acceptor_.open(endpoint.protocol());

It binds to 127.0.0.1. When a client is connecting externally, the client is using the IP address 192.168.0.107 or something similar. The server implemented by BOOST ASIO just simply refuses the client connection.

So is there a way to deal with this? I think for apache2, the apache2 is not required to bind to a specific IP, any client requests from any server interface (provided there are multiple interfaces) can connect to apache2.

Is there a way to solve it? Or there's no way and I have to fix the server external IP?

Thanks.

2

There are 2 answers

0
Cornstalks On BEST ANSWER

Bind to 0.0.0.0. That's the "wildcard" that listens on all interfaces for any incoming connection.

If you bind to 127.0.0.1, your server will only accept incoming connections over the loopback, which won't let you client connect (since your client isn't using the loopback).

0
Galimov Albert On

You can create a endpoint to listen on any IP like this:

boost::asio::ip::tcp::endpoint ep(boost::asio::ip::tcp::v4(), listen_port );