Boost ASIO Simple UDP Send Packet Example

Update: I have written a simple Fire-And-Forget wrapper class for sending datagrams via UDP can be found here. It handles simple transmission use cases while hiding the (sometimes confusing) boost::asio details. However, if you are interested in the details then read on!

Boost.ASIO is great but if you don’t use it everyday it can be hard to remember how to use it to do even the simplest of things. I have included below a sample of simply sending a packet via UDP (ipv4), see the function called send_message(), this example code aims to be as minimal as it can be:

Those spouting software engineering dogma will often tell you to steer well clear of UDP for the usual, well understood reasons, but for a certain type of application where very low latency is important, it just can’t be beat!!

#include 
#include 
using namespace boost::asio;
//
// Send a string via UDP to the specified destination
// ip addresss at the specified port (point-to-point
// not broadcast)
//
bool send_udp_message(const std::string& message, const std::string& destination_ip,
						const unsigned short port) {
	io_service io_service;
	ip::udp::socket socket(io_service);
	// Create the remote endpoint using the destination ip address and
	// the target port number.  This is not a broadcast
	auto remote = ip::udp::endpoint(ip::address::from_string(destination_ip), port);
	try {
	
		// Open the socket, socket's destructor will
		// automatically close it.
		socket.open(boost::asio::ip::udp::v4());
		// And send the string... (synchronous / blocking)
		socket.send_to(buffer(message), remote);
	
	} catch (const boost::system::system_error& ex) {
		// Exception thrown!
		// Examine ex.code() and ex.what() to see what went wrong!
		return false;
	}
	return true;
}

This is the bare-bones code, no error reporting etc. Also it won’t broadcast, to allow for broadcast you need to include the following two lines and supply a broadcast ip address when calling the function. Be careful if broadcasting a lot of data as it can really overload & mess-up network equipment!

socket_base::broadcast option(true);
socket.set_option(option);