boost async_receive_from ip过滤器 [英] boost async_receive_from ip filter

查看:677
本文介绍了boost async_receive_from ip过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 boost :: asio 在udp端口捕获数据包。我只是新的提振。
如何使 async_receive_from 将数据复制到仅缓冲指定源ip的数据包?

I'm using boost::asio to capture packets on udp port. I'm just new to boost. How can I make async_receive_from copy data to buffer only packets with specified source ip?

推荐答案

取决于捕获数据包的含义,像这样的代码可以工作。这是修改从Boost Asio Async UDP示例。 socket _ 连接到指定的端口的本地接口如果你设置port为0我相信它侦听所有端口。




一旦您使用 async_receive_from 接收到数据包,它也将返回 sender_endpoint_ handle_receive_from 函数只需添加一个条件语句来检查所需的 sender_endpoint _ 和将数据复制到缓冲区。

Depending on what you mean by capture packets, some code like this would work. This is modified from Boost Asio Async UDP example. socket_ is connected to a local interface at a specified port if you set port to 0 I believe it listens on all the ports.

Once you receive a packet using async_receive_from, it will also return sender_endpoint_ from the decoded datagram(i.e. where did the packet in question come from.) In your handle_receive_from function just add a conditional statement to check for desired sender_endpoint_ and "copy the data to buffer".

class server
{ 
public: 
    server(boost::asio::io_service& io_service, short port)
    : io_service_(io_service),
    socket_(io_service, udp::endpoint(udp::v4(), port))
    {
        boost::asio::socket_base::receive_buffer_size option(1<<12); <br>
        socket_.set_option(option);
        start_receive(); 
    }

    void handle_receive_from(const boost::system::error_code& error,
        size_t bytes_recvd)
    {
        if (!error && bytes_recvd > 0)
        {
           if(sender_endpoint_ == <desired_IP_here>) 
               messages_.push(data_);
        } 
        start_receive();
    }

private: 
    boost::asio::io_service& io_service_; 
    udp::socket socket_;
    udp::endpoint sender_endpoint_;
    enum { max_length = 256}; 
    boost::array < boost::uint32_t, max_length > data_; 
    std::queue<boost::array<boost::uint32_t, max_length> messages_; 

    void start_receive()
    {
        socket_.async_receive_from(
            boost::asio::buffer(data_, (sizeof(boost::uint32_t)*max_length)),
            sender_endpoint_,
            boost::bind(&server::handle_receive_from, this,
            boost::asio::placeholders::error,
            boost::asio::placeholders::bytes_transferred));

    }
};

几乎忘了 - 主要功能!

Almost forgot - main function!

int main(void) 
{
    boost::asio::io_service io_service;
    int port_rx = 0;


    using namespace std;
    server rx(io_service, port_rx);
    io_service.run();

    return 0;
}

希望这有助!

这篇关于boost async_receive_from ip过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆