I need to get the source IP for a datagram in a UDP server I'm writing using boost ASIO. In the example udp datagram server the line:
Note: my current code is identical to the existing udp async server example in the boost asio documentation.
socket_.async_receive_from(
boost::asio::buffer(data_, max_length), sender_endpoint_,
boost::bind(&server::handle_receive_from, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
Is passing error and bytes_transferred. I also need the address of the message.
Now I know I can use sender_endpoint_.address().to_string() directly, but I I would like to pass this in as a parameter.
So I tried placing sender_开发者_如何学编程endpoint_.address() in as a parameter. i.e.
socket_.async_receive_from(
boost::asio::buffer(data_, MAX_LENGTH), sender_endpoint_,
boost::bind(&server::handle_receive_from, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred,
sender_endpoint_.address()));
But the result is 0.0.0.0 when read from handle_receive_from. However, if I simply access the sender_endpoint_.address() inside handle_receive_from I get 127.0.0.1 which is correct.
How do pass this correctly? I need this because there are going to be multiple threads calling io_service.run() so a packet from another source may overwrite sender_endpoint and I need to be able to reply to that source packet.
I think that if you access sender_endpoint_.address() in your handler before you set up another async handler, it will be fine and not overridden. You do call async_receive_from again in your handler, right, to be ready to receive another packet?
In your second code block, where you try sender_endpoint_.address() as a parameter, sender_endpoint_.address() is getting called when you set up the handler, not being executed by the handler when a packet is received. That's why it'll always be 0.0.0.0.
精彩评论