UDP Connect Always Succeeds

2019-08-25 18:25发布

问题:

I am using Boost ASIO to connect to an Arduino Nano with an Ethernet Shield over ethernet. This is the Arduino setup:

#include <EtherCard.h>
ether.staticSetup("10.0.0.4", "10.0.0.1");
ether.udpServerListenOnPort(&callback_function, 1337);

This is my C++ code that connects to it:

Header

#include <boost/asio.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <boost/bind.hpp>
#include <boost/thread.hpp>
#include <boost/system/error_code.hpp>
#include <boost/system/system_error.hpp>

boost::system::error_code error_1;
boost::shared_ptr <boost::asio::io_service> io_service_1;
boost::shared_ptr <boost::asio::ip::udp::socket> socket_1;

Initialize

// 1. reset io service      
io_service_1.reset();
io_service_1 = boost::make_shared <boost::asio::io_service> ();

// 2. create endpoint
boost::asio::ip::udp::endpoint remote_endpoint(
    boost::asio::ip::address::from_string("10.0.0.4"), 
    1337
);

// 3. reset socket
socket_1.reset(new boost::asio::ip::udp::socket(*io_service_1));                

// 4. connect socket
socket_1->async_connect(remote_endpoint, socket_1_connect_callback);

// 5. start io_service_1 run thread after giving it work
boost::thread t(boost::bind(&boost::asio::io_service::run, *&io_service_1));    

Callback

function socket_1_connect_callback (const boost::system::error_code& error_1)
{
    // 1. check for errors
    if (error_1) 
    {
        std::cerr << "error_1.message() >> " << error_1.message().c_str() << std::endl;
        return;
    }
    else
    {
        INFO << "connection succeeded";
    }   

    return; 
}

The socket connects every time, even if the Arduino is not powered. Why does it not fail to connect?

回答1:

By definition, UDP is connection-less protocol. 'Connecting' a UDP socket is simply a convenience operation, which allows you to than send datagrams on that socket without specifying recipient - it uses the one you gave to a connect call.

But other than that, it does nothing. There is really no way to check if someone is listening on the other side of UDP, unless you implement a request/response scheme yourself.

The fact that you are using Boost.Asio adds nothing to this basic fact.