Search code examples
c++socketsboostboost-asioasio

Different ways of opening and binding a UDP socket with Boost Asio c++


I'm trying to create a simple UDP broadcast class in c++ using the Boost Asio library. Specifically, in the main class I'd like to instantiate a socket to both send and receive data. But I've seen three different ways of doing so, and I wanted to ask if anyone knew the difference? These are the methods I've seen:

The first after creating the socket using a io_context, opens it:

socket.open(udp::v4());

I've read somewhere that it works also in receiving after sending a packet, because calling socket.send(...) automatically binds the socket to a local endpoint (i.e. host address and a random port); but at this point anyone wanting to send a packet to this specific socket, how would be able to do so if the local endpoint is kind of "generated random" (the port is not known..).

The second method I've seen is first opening the socket then binding it to a local endpoint:

socket.open(udp::v4());
socket.bind(local_endpoint);

Finally the third method, consists of creating the socket with already a local endpoint, and use it without calling open():

udp::socket socket(io_context, local_endpoint);

So what would be the difference between the three, and would they all work? What would be the best way?

Thank you in advance!


Solution

  • The first method will create a socket without binding to a specific port. This is fine if you don't care about someone initiating the messages with you. IE: You send a message to a recipent, they can reply back because they received the sender's IP and Port along with the message.

    If you want someone to be able to message you on a specific IP and port, you can initialize your socket like so:

    socket_(io_service, udp::endpoint(udp::v4(), port))