使用boost :: asio获取UDP套接字远程地址

时间:2018-03-21 08:02:45

标签: c++ sockets udp boost-asio

我想获取响应UDP广播的设备的IP地址。在以下代码中,我执行UDP广播以查找设备。当设备响应时,我尝试使用remote_endpoint()获取远程端点。

然而,应用程序因异常而崩溃 boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::system::system_error> >: remote_endpoint: Socket is not connected

由于我对C ++和boost :: asio很陌生,有人可以解释我需要更改代码以获取远程端点的IP地址。

#include <boost/array.hpp>
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/bind.hpp>
#include <iostream>

class udpFind {
public:
    udpFind(boost::asio::io_context& service, boost::asio::ip::udp::endpoint listen_endpoint, unsigned int port)
    : broadcastEndpoint_(boost::asio::ip::address_v4::broadcast(), port),
    timer(service),
    socket_(service, listen_endpoint)
    {
        socket_.set_option(boost::asio::ip::udp::socket::reuse_address(true));
        socket_.set_option(boost::asio::socket_base::broadcast(true));

        find();
    }

    void find () {
        std::array<unsigned int, 2> data = {255, 255};
        for (auto it = std::begin(data); it != std::end(data); ++it)
            std::cout << *it;
        socket_.async_send_to(
                              boost::asio::buffer(data, 2), broadcastEndpoint_,
                              boost::bind(&udpFind::handle_send, this,
                                          boost::asio::placeholders::error,
                                          boost::asio::placeholders::bytes_transferred));
    }

    void handle_receive(const boost::system::error_code& error,
                        std::size_t bytes_transferred)
    {
        // Read has finished, so cancel the timer.
        timer.cancel();
        if (!error) {
            std::cout << "Received Data" << bytes_transferred << std::endl

            boost::asio::ip::udp::endpoint local_ep = socket_.local_endpoint();
            boost::asio::ip::udp::endpoint remote_ep = socket_.remote_endpoint();
        }
    }

    void handle_retry(const boost::system::error_code& error) {
        std::cout << "retrying"  << std::endl;
        find();
    }


    void handle_timeOut(const boost::system::error_code& error) {
        if (!error) {
            std::cout << "Timeout"  << std::endl;
            // Timer has expired cancel read operation
            socket_.cancel();
            timer.expires_from_now(boost::posix_time::milliseconds(10000));
            timer.async_wait(boost::bind(&udpFind::handle_retry,
                                         this, boost::asio::placeholders::error));
        }
    }


    void handle_send(const boost::system::error_code& error, std::size_t bytes_transferred)
    {
        std::cout << "Sent Data "  << bytes_transferred << std::endl;
        buffer_= {};
        socket_.async_receive_from(
                                   boost::asio::buffer(buffer_), broadcastEndpoint_,
                                   boost::bind(&udpFind::handle_receive, this,
                                               boost::asio::placeholders::error,
                                               boost::asio::placeholders::bytes_transferred));

        timer.expires_from_now(boost::posix_time::milliseconds(10000));
        timer.async_wait(boost::bind(&udpFind::handle_timeOut,
                                     this, boost::asio::placeholders::error));
    }

private:
    boost::asio::ip::udp::socket socket_;
    std::array<char, 128> buffer_;
    boost::asio::ip::udp::endpoint broadcastEndpoint_;
    boost::asio::deadline_timer timer;
};

int main()
{
    boost::asio::io_context service;
    boost::asio::ip::udp::endpoint listen_endpoint(boost::asio::ip::address::from_string("0.0.0.0"), 0);
    udpFind find(service, listen_endpoint, 9000);
    service.run();
}

1 个答案:

答案 0 :(得分:1)

我提到the other day&#34;端点&amp; async_receive_from的参数不适用于此,我认为它是输出参数&#34;

socket_.async_receive_from(
                           boost::asio::buffer(buffer_), broadcastEndpoint_,
                           boost::bind(&udpFind::handle_receive, this,
                                       boost::asio::placeholders::error,
                                       boost::asio::placeholders::bytes_transferred));

在这里你传递一个broadcastEndpoint的引用,这可能不是你想要做的。 The documentation states该参数为sender_endpoint

  
      
  • sender_endpoint

         

    接收数据报远程发送方端点的端点对象。调用者保留sender_endpoint对象的所有权,调用者必须保证它在调用处理程序之前有效。

  •   

因此,解决方案只是添加一个变量来接收远程端点:

<强> Live On Coliru

#include <boost/array.hpp>
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/bind.hpp>
#include <iostream>

class udpFind {
public:
    udpFind(boost::asio::io_context& service, boost::asio::ip::udp::endpoint listen_endpoint, unsigned int port)
    : broadcastEndpoint_(boost::asio::ip::address_v4::broadcast(), port),
      timer(service),
      socket_(service, listen_endpoint)
    {
        socket_.set_option(boost::asio::ip::udp::socket::reuse_address(true));
        socket_.set_option(boost::asio::socket_base::broadcast(true));

        find();
    }

    void find () {
        std::array<unsigned int, 2> data = {{255, 255}};
        for (auto it = std::begin(data); it != std::end(data); ++it)
            std::cout << *it;

        socket_.async_send_to(
                              boost::asio::buffer(data, 2), broadcastEndpoint_,
                              boost::bind(&udpFind::handle_send, this,
                                          boost::asio::placeholders::error,
                                          boost::asio::placeholders::bytes_transferred));
    }

    void handle_receive(const boost::system::error_code& error,
                        std::size_t bytes_transferred)
    {
        // Read has finished, so cancel the timer.
        timer.cancel();
        if (!error) {
            std::cout << "Received Data" << bytes_transferred << " from " << senderEndpoint_ << std::endl;
        }
    }

    void handle_retry(const boost::system::error_code& error) {
        std::cout << "retrying"  << std::endl;
        find();
    }


    void handle_timeOut(const boost::system::error_code& error) {
        if (!error) {
            std::cout << "Timeout"  << std::endl;
            // Timer has expired cancel read operation
            socket_.cancel();
            timer.expires_from_now(boost::posix_time::milliseconds(10000));
            timer.async_wait(boost::bind(&udpFind::handle_retry,
                                         this, boost::asio::placeholders::error));
        }
    }


    void handle_send(const boost::system::error_code& error, std::size_t bytes_transferred)
    {
        std::cout << "Sent Data "  << bytes_transferred << " (" << error.message() << ")" << std::endl;
        buffer_= {};
        socket_.async_receive_from(
                                   boost::asio::buffer(buffer_), senderEndpoint_,
                                   boost::bind(&udpFind::handle_receive, this,
                                               boost::asio::placeholders::error,
                                               boost::asio::placeholders::bytes_transferred));

        timer.expires_from_now(boost::posix_time::milliseconds(10000));
        timer.async_wait(boost::bind(&udpFind::handle_timeOut,
                                     this, boost::asio::placeholders::error));
    }

private:
    boost::asio::ip::udp::endpoint broadcastEndpoint_;
    boost::asio::deadline_timer timer;
    boost::asio::ip::udp::socket socket_;
    boost::asio::ip::udp::endpoint senderEndpoint_;
    std::array<char, 128> buffer_;
};

int main()
{
    boost::asio::io_context service;
    boost::asio::ip::udp::endpoint listen_endpoint(boost::asio::ip::address::from_string("0.0.0.0"), 0);
    udpFind find(service, listen_endpoint, 9000);
    service.run();
}