簡體   English   中英

Boost Asio UDP服務器設置套接字監聽指定的IP

[英]Boost Asio UDP server set socket to listen on specified IP

當我在UDP服務器上工作時,我通常將套接字設置為偵聽指定端口並接受任何IP。 請記住,同步接收在這里正常工作。

std::unique_ptr<boost::asio::ip::udp::socket> socketUDP;    
socketUDP.reset(new udp::socket(io_serviceUDP, udp::endpoint(udp::v4(), 9999)));

但是,我真的希望有2個不同的服務器應用程序在同一個端口(9999)監聽,但只接受一個I​​P(我已經知道IP)。 每個應用程序都有自己的客戶端和自己的IP。 但由於某種原因,以下不起作用(在應用程序中沒有收到任何數據包,而Wireshark可以看到它)

socketUDP.reset(new udp::socket(m_io_serviceUDP, udp::endpoint(asio::ip::address::from_string("169.254.1.2"), 9999)));

請注意: 1)根據以下答案: 使用Boost.Asio進行廣播問題,這實際上應該有效。 當然,由於我遺漏了一些東西,我的理解並不完全正確

2)提供的IP有效,工作,發送數據(由wireshark確認)並可以ping通

問題是你的socketUDP沒有配置:

set_option(boost::asio::ip::udp::socket::reuse_address(true));

但是,簡單地在套接字上調用上面的行是行不通的,因為在套接字綁定到端點之前必須調用reuse_address ...但是你正在用一個endpoint構建udp::socket ,它打開它並將它綁定到端點,請參閱basic_datagram_socket

解決方案是調用只接受io_service的構造函數; 打開它,設置reuse_address選項然后 bind它,例如:

// construct the socket
boost::asio::ip::udp::socket  socket_(io_service_);

// open it
boost::asio::ip::udp::endpoint rx_endpoint_(udp::v4(), 9999);
socket_.open(rx_endpoint_.protocol(), error);
if (error)
  return false;

// then set it for reuse and bind it
socket_.set_option(boost::asio::ip::udp::socket::reuse_address(true));
socket_.bind(rx_endpoint_, error);
if (error)
   return false;

// set multicast group, etc.
socket_.set_option(boost::asio::ip::multicast::join_group(ip_address));
...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM