Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does boost::asio figure out what port to connect to?

So I decided to take a step forward after my C++ course, by learning how to do some networking.

After following the example of how to use boost::asio to make a synchronous client, everything went well, but I was stumped when trying to figure out what part of the program actually deals with the port.

I understand you enter an IP address (eg. I used 127.0.0.1 as the argument for the program. I ran the code via command line: # client 127.0.0.1

Also, the server side of the code, runs on port 13, shown here: http://www.boost.org/doc/libs/1_52_0/doc/html/boost_asio/tutorial/tutdaytime2.html

Here is the full code from the website: (also can be found here: http://www.boost.org/doc/libs/1_52_0/doc/html/boost_asio/tutorial/tutdaytime1.html

//
// client.cpp
// ~~~~~~~~~~
//
// Copyright (c) 2003-2012 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#include <iostream>
#include <boost/array.hpp>
#include <boost/asio.hpp>

using boost::asio::ip::tcp;

int main(int argc, char* argv[])
{
  try
  {
    if (argc != 2)
    {
      std::cerr << "Usage: client <host>" << std::endl;
      return 1;
    }

    boost::asio::io_service io_service;

    tcp::resolver resolver(io_service);
    tcp::resolver::query query(argv[1], "daytime");
    tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);

    tcp::socket socket(io_service);
    boost::asio::connect(socket, endpoint_iterator);

    for (;;)
    {
      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)
        break; // Connection closed cleanly by peer.
      else if (error)
        throw boost::system::system_error(error); // Some other error.

      std::cout.write(buf.data(), len);
    }
  }
  catch (std::exception& e)
  {
    std::cerr << e.what() << std::endl;
  }

  return 0;
}
like image 299
TheAJ Avatar asked Feb 18 '23 05:02

TheAJ


1 Answers

The port is set in this line:

tcp::resolver::query query(argv[1], "daytime");

The string "daytime" references an accepted name for the daytime protocol, and it uses a well-known port. If you are on a Linux or Mac OSX machine, you can check the file /etc/services to the name-to-port mappings.

like image 155
Some programmer dude Avatar answered Feb 22 '23 21:02

Some programmer dude