H
H
HamsterGamer2022-03-10 14:48:38
C++ / C#
HamsterGamer, 2022-03-10 14:48:38

How can I bind my program to only one port using boost::asio?

The essence of the task is as follows, this is a peer-to-peer connection, in fact there is a swarm and I need to connect to all its participants. In this case, my port (which I will set) will be stored in this swarm along with the ip address when I make a request to get a list of members from this swarm (I will become the same member of the swarm). But the problem is that I don't understand how you can occupy a port even before connecting, bind each socket to these participants through this port, and at the same time create an acceptor for this port.
Explanation:
This is how I make the connection (here the port (which I want to connect from my side ) is not indicated and it is not clear to me what it will be?):

void client::do_connect(ba::ip::tcp::resolver::iterator endpoint) {
    auto self(Get());
    ba::async_connect(socket_, std::move(endpoint), [this, self](boost::system::error_code ec,  const ba::ip::tcp::resolver::iterator&) {
        if (!ec) {
            ... // полезная работа если подключились
        } else try_again();
    });
    timeout_.expires_from_now(connection_waiting_time + epsilon);
}

After I am connected, new participants will already contact me on the port that I specified (when I made a request to this swarm) and it’s clear which port the socket connects to.
tcp::endpoint endpoint(tcp::v4(), "2007");
tcp::acceptor acceptor_(io_service, endpoint);
// ...
void Listener::do_accept() {
    acceptor_.async_accept(socket_,
                           [this](boost::system::error_code ec){
       if (!ec) {
           ... // делаем новое соединение с сокетом
       }
       do_accept();
    });
}

But how can I make it so that the entire program uses the same port on all sockets? Or in the case of connection it does not matter?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question