[英]Read boost::asio UDP Broadcast Response
我正在嘗試使用boost :: asio來實現簡單的設備發現協議。 基本上,我想發送帶有2字節有效負載的廣播消息(端口9000)。 然后從設備讀取響應(假設當前存在)。 在Wireshark中,我可以看到廣播已發送並且設備正在響應。 但是,在我的示例代碼中,我獲得了在讀取的UDP中返回的字節為0,而不是30字節的數據。
No. Time Source Destination Protocol Length
1 0.00000 192.168.0.20 255.255.255.255 UDP 44 52271 -> 9000 Len = 2
2 0.00200 192.168.0.21 192.168.0.20 UDP 72 9000 -> 52271 Len = 30
我應該從不同於broadcastEndpoint的端點讀取嗎? 如何獲得終點?
我是asio的新手,正在嘗試教自己,但我無法做錯我的工作。
#include <boost/array.hpp>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <iostream>
class udp_find {
public:
udp_find(boost::asio::io_context& service, unsigned int port)
: broadcastEndpoint_(boost::asio::ip::address_v4::broadcast(), port),
socket_(service)
{
socket_.open(boost::asio::ip::udp::v4());
socket_.set_option(boost::asio::ip::udp::socket::reuse_address(true));
socket_.set_option(boost::asio::socket_base::broadcast(true));
boost::array<unsigned int, 2> data = {255, 255};
socket_.async_send_to(
boost::asio::buffer(data, 2), broadcastEndpoint_,
boost::bind(&udp_find::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)
{
std::cout << "Received Data" << bytes_transferred << std::endl;
}
void handle_send(const boost::system::error_code& error, std::size_t bytes_transferred)
{
std::cout << "Sent Data" << bytes_transferred << std::endl;
socket_.async_receive_from(
boost::asio::buffer(buffer_), broadcastEndpoint_,
boost::bind(&udp_find::handle_receive, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
private:
boost::asio::ip::udp::socket socket_;
boost::array<char, 128> buffer_;
boost::asio::ip::udp::endpoint broadcastEndpoint_;
};
int main()
{
boost::asio::io_context service;
udp_find(service, 9000);
service.run();
}
您的第一個問題是Udefined Behavior 。
您對udp_find
類型的臨時對象啟動異步操作。 該對象在構造后立即被銷毀,因此即使在開始任何異步工作( service.run()
)之前,該對象都不存在。
通過將udp_find
為局部變量而不是臨時變量,可以輕松解決此問題:
udp_find op(service, 9000);
現在為我發送作品。 您將要測試接收是否也正常。 在我的netstat
輸出中,似乎UDP套接字已綁定到臨時端口。 將數據報發送到該端口可以使測試成功。
您可能想要在接收之前實際綁定/連接到廣播地址( async_receive_from
的endpoint&
參數並不適用async_receive_from
,我認為這是一個輸出參數)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.