Reputation: 13
I am working with libscapi and keep getting errors when trying to establish a connection with boost::asio::connect. I have been trying to get simple examples to work (like the one below) but I always get the "connection refused" error. I guess it must be a very simple mistake but I just don't understand it.
#include <boost/asio.hpp>
#include <iostream>
int main(int argc, char* argv[]) {
boost::asio::io_service io_service;
boost::asio::ip::tcp::endpoint endpoint;
boost::asio::ip::tcp::resolver resolver(io_service);
boost::asio::ip::tcp::resolver::query query("www.boost.org", "http");
boost::asio::ip::tcp::resolver::iterator iter = resolver.resolve(query);
boost::asio::ip::tcp::resolver::iterator end; // End marker.
while (iter != end)
{
boost::asio::ip::tcp::endpoint endpoint = *iter++;
std::cout << endpoint << std::endl;
}
boost::asio::ip::tcp::socket socket(io_service);
socket.connect(endpoint);
}
Upvotes: 1
Views: 5285
Reputation: 51
The boost asio TCP daytime client example assumes you have access to a daytime service running on its default port 13 on some server. Without the server running on port 13, you will receive the "connection refused" message.
To test the example locally, you must first install xinetd (Debian 10 - Buster), enable the "tcp" daytime service in file /etc/xinetd.d/daytime, and restart xinetd with "sudo systemctl restart xinetd.service". FreeBSD Unix uses inetd. Once the daytime service is running, then execute the boost example. Enter "localhost" or "127.0.0.1" for the "host" when running the example. Somewhere inside of asio, tcp::resolver maps the text "daytime" to port 13.
The 2nd half of the example, "TCP daytime server", assumes you do not have a local server running on port 13. Either "sudo systemctl stop xinetd.service" or disable the "tcp" daytime service and restart xinetd as above. You may need to use sudo to run the server example if you get a "bind: Permission denied". Once the server is running in a window, open a different window and run the client example again.
Upvotes: 2
Reputation: 20936
You are passing default constructed endpoint for connect
, which is just not valid.
When you have a list of endpoints specified by [iter,end)
iterators, you should check each one of them passing it to connect
:
boost::asio::ip::tcp::socket socket(io_service);
while (iter != end)
{
boost::asio::ip::tcp::endpoint endpoint = *iter++;
std::cout << endpoint << std::endl;
boost::system::erroc_code err;
socket.connect(endpoint,err);
if ( !err ) // there is no error
{
// connection is established, we can break loop
break;
}
else {
std::cout << "ups, we have problem" << std::endl;
}
}
Simpler version would be to use free connect function which takes both iterators:
boost::asio::ip::tcp::socket socket(io_service);
boost::system::error_code err;
boost::asio::connect(socket,iter,end,err);
if (!err)
std::cout << "connected" << std::endl;
Upvotes: 0