asio async_receive 如何获取发件人 IP 地址

时间:2021-03-20 12:51:02

标签: c++ boost-asio knx

我编写了一个小型协议栈来连接到 KNX/IP 路由器。机制如下:

  • Discovery_Channel:为了发现,客户端向多播地址 224.0.23.12 发送一个 UDP/IP 数据包。 KNX/IP 路由器侦听此多播地址并回复。 KNX/IP 路由器可能连接到多个 KNX 媒体,因此答案包含客户端可以连接到的具有 IP 地址和端口的服务列表。
  • Communication_Channel:从所有 KNX/IP 路由器发现的服务会呈现给用户,以选择应连接到哪个服务。

问题是来自 KNX/IP 路由器的答案有时不包含有效的 IP 地址,而仅包含 0.0.0.0。在这种情况下,我需要从数据包来源处获取 IP 地址。但是我怎么能用(非增强版)asio 得到这个?

我的代码如下:

/** client socket */
asio::ip::udp::socket m_socket;

/** search request */
void search_request(
    const IP_Host_Protocol_Address_Information & remote_discovery_endpoint = IP_Host_Protocol_Address_Information({224, 0, 23, 12}, Port_Number),
    const std::chrono::seconds search_timeout = SEARCH_TIMEOUT);

/** search response initiator */
void Discovery_Channel::async_receive_response() {
    /* prepare a buffer */
    m_response_data.resize(256);

    /* async receive */
    m_socket.async_receive(
        asio::buffer(m_response_data),
        std::bind(&Discovery_Channel::response_received, this, std::placeholders::_1, std::placeholders::_2));
}

/** response received handler */
void Discovery_Channel::response_received(const std::error_code & error, std::size_t bytes_transferred) {
    // here the answer provided in m_response_data gets interpreted.
    // @todo how to get the IP address of the sender?

    /* start initiators */
    async_receive_response();
}

那么如何在 Discovery_Channel::response_received 方法中检索发送方的 IP 地址?我基本上只有 m_response_data 中的数据包数据可用。

1 个答案:

答案 0 :(得分:1)

在数据报套接字上,您可以(应该,很可能)使用 async_receive_from

它需要一个端点变量的引用,该变量将在成功时设置为远程端点。

相关问题