简体   繁体   中英

boost async_receive_from ip filter

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?

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(ie 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;
}

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM