The link I'm using for the asio code is https://www.boost.org/doc/libs/1_55_0/doc/html/boost_asio/tutorial/tutdaytime1.html
#include <iostream>
#include <boost/asio.hpp>
#include <boost/array.hpp>
// #include <src.hpp>
using boost::asio::ip::tcp;
int main(int argc, char *argv[])
{
std::cout << "Started" << std::endl;
try{
boost::asio::io_context io;
boost::asio::steady_timer t(io, boost::asio::chrono::seconds(5));
tcp::resolver resolver(io);
tcp::resolver::results_type endpoints = resolver.resolve(argv[1],"daytime");
tcp::socket socket(io);
boost::asio::connect(socket,endpoints);
boost::array<char,128> buf;
boost::system::error_code error;
size_t len = socket.read_some(boost::asio::buffer(buf), error);
if (error == boost::asio::error::eof)
{
std::cout << "No Errors" << std::endl;
}
else if(error){
throw boost::system::system_error(error);
}
std::cout << "Data is: ";
std::cout.write(buf.data(), len);
io.run();
}
catch(std::exception& e){
std::cerr << e.what() << std::endl;
}
return 0;
}
I get a segmentation fault trying to run code for a daytime tcp client and I don't have any idea why. It says the buffer function auto prevents buffer overflows on the reference. I just need it to not give me a segmentation fault, I'm not experienced with either c++ or networking.
Likely segfaulting because you're using command line arguments not passed?
Either hard code the argument:
tcp::resolver::results_type endpoints = resolver.resolve("127.0.0.1", "daytime");
Or instead, check that arguments are present:
if (argc < 2) {
std::cerr << "Usage: " << argv[0] << " HOSTNAME" << std::endl;
return 1;
}