boost::asio::ip::tcp::socket - 如何绑定到特定的本地端口

2024-03-12

我正在制作一个客户端套接字。

为了让测试人员更轻松,我想指定套接字将使用的网卡和端口。

昨天,在谷歌搜索中,我发现:将 boost asio 绑定到本地 tcp 端点 https://stackoverflow.com/questions/8416917/binding-boost-asio-to-local-tcp-endpoint

通过执行 open、bind 和 async_connect,我能够绑定到特定的网卡,并且开始在 Wireshark 中看到流量。

然而,Wireshark 报告该套接字已被分配了一个随机端口,而不是我指定的端口。我认为如果端口正在使用中,它会填写传递给绑定方法的 error_code。

我究竟做错了什么?

这是我的最小示例,从我的真实解决方案中提取和编辑。

// Boost Includes
#include <boost/asio.hpp>
#include <boost/atomic.hpp>
#include <boost/bind.hpp>
#include <boost/thread.hpp>
#include <boost/thread/condition_variable.hpp>

// Standard Includes
#include <exception>
#include <memory>
#include <string>
#include <sstream>


boost::asio::io_service        g_ioService;                     /** ASIO sockets require an io_service to run on*/
boost::thread                  g_thread;                        /** thread that will run the io_service and hence where callbacks are called*/
boost::asio::ip::tcp::socket   g_socket(g_ioService);           /** Aync socket*/
boost::asio::ip::tcp::resolver g_resolver(g_ioService);         /** Resolves IP Addresses*/

//--------------------------------------------------------------------------------------------------
void OnConnect(const boost::system::error_code & errorCode, boost::asio::ip::tcp::resolver::iterator endpoint)
{
    if (errorCode || endpoint == boost::asio::ip::tcp::resolver::iterator())
    {
        // Error - An error occured while attempting to connect
        throw std::runtime_error("An error occured while attempting to connect");
    }

    // We connected to an endpoint

    /*
    // Start reading from the socket
    auto callback = boost::bind(OnReceive, boost::asio::placeholders::error);
    boost::asio::async_read_until(g_socket, m_receiveBuffer, '\n', callback);
    */
}


//--------------------------------------------------------------------------------------------------
void Connect()
{
    const std::string hostName = "10.84.0.36";
    const unsigned int port = 1007;

    // Resolve to translate the server machine name into a list of endpoints
    std::ostringstream converter;
    converter << port;
    const std::string portAsString = converter.str();

    boost::asio::ip::tcp::resolver::query query(hostName, portAsString);

    boost::system::error_code errorCode;
    boost::asio::ip::tcp::resolver::iterator itEnd;
    boost::asio::ip::tcp::resolver::iterator itEndpoint = g_resolver.resolve(query, errorCode);

    if (errorCode || itEndpoint == itEnd)
    {
        // Error - Could not resolve either machine
        throw std::runtime_error("Could not resolve either machine");
    }

    g_socket.open(boost::asio::ip::tcp::v4(), errorCode);
    if (errorCode)
    {
        // Could open the g_socket
        throw std::runtime_error("Could open the g_socket");
    }

    boost::asio::ip::tcp::endpoint localEndpoint(boost::asio::ip::address::from_string("10.86.0.18"), 6000);
    g_socket.bind(localEndpoint, errorCode);
    if (errorCode)
    {
        // Could bind the g_socket to local endpoint
        throw std::runtime_error("Could bind the socket to local endpoint");
    }

    // Attempt to asynchronously connect using each possible end point until we find one that works
    boost::asio::async_connect(g_socket, itEndpoint, boost::bind(OnConnect, boost::asio::placeholders::error, boost::asio::placeholders::iterator));
}

//--------------------------------------------------------------------------------------------------
void g_ioServiceg_threadProc()
{
    try
    {
        // Connect to the server
        Connect();

        // Run the asynchronous callbacks from the g_socket on this thread
        // Until the io_service is stopped from another thread
        g_ioService.run();
    }
    catch (...)
    {
        throw std::runtime_error("unhandled exception caught from io_service g_thread");
    }
}

//--------------------------------------------------------------------------------------------------
int main()
{
    // Start up the IO service thread
    g_thread.swap(boost::thread(g_ioServiceg_threadProc));

    // Hang out awhile
    boost::this_thread::sleep_for(boost::chrono::seconds(60));

    // Stop the io service and allow the g_thread to exit
    // This will cancel any outstanding work on the io_service
    g_ioService.stop();

    // Join our g_thread
    if (g_thread.joinable())
    {
        g_thread.join();
    }

    return true;
}

正如您在下面的屏幕截图中看到的,选择了随机端口 32781,而不是我请求的端口 6000。


我怀疑主题发起者是否仍然对这个问题感兴趣,但对于像我这样的所有未来的寻求者来说,这里是解决方案。

这里的问题是boost::asio::connect在调用之前关闭套接字connect对于所提供范围内的每个端点:

来自 boost/asio/impl/connect.hpp:

template <typename Protocol BOOST_ASIO_SVC_TPARAM,
    typename Iterator, typename ConnectCondition> 
Iterator connect(basic_socket<Protocol BOOST_ASIO_SVC_TARG>& s,
    Iterator begin, Iterator end, ConnectCondition connect_condition,
    boost::system::error_code& ec)
{ 
  ec = boost::system::error_code();

  for (Iterator iter = begin; iter != end; ++iter)
  {
    iter = (detail::call_connect_condition(connect_condition, ec, iter, end));
    if (iter != end)
    {
      s.close(ec); // <------
      s.connect(*iter, ec);
      if (!ec)
        return iter;
    }
...
} 

这就是重置绑定地址的原因。为了保持它的绑定,可以使用socket.connect/async_connect(...)直接地

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

boost::asio::ip::tcp::socket - 如何绑定到特定的本地端口 的相关文章

随机推荐