views:

199

answers:

1

It seems boost::asio defines a separate endpoint class for each protocol, which is irritating if you want to perform both UDP and TCP operations on a particular endpoint (have to convert from one to the other). I'd always just thought of an endpoint as an IP address (v4 or v6) and the port number, regardless of TCP or UDP. Are there significant differences that justify separate classes? (i.e. couldn't both tcp::socket and udp::socket accept something like ip::endpoint?)

+1  A: 

The sockets are created differently

socket(PF_INET, SOCK_STREAM)

for TCP, and

socket(PF_INET, SOCK_DGRAM)

for UDP.

I suspect that is the reason for the differing types in Boost.Asio. See man 7 udp or man 7 tcp for more information, I'm assuming Linux since you didn't tag your question.

To solve your problem, extract the IP and port from a TCP endpoint and instantiate a UDP endpoint.

#include <boost/asio.hpp>

#include <iostream>

int
main()
{
    using namespace boost::asio;
    ip::tcp::endpoint tcp( 
            ip::address::from_string("127.0.0.1"),
            123
            );

    ip::udp::endpoint udp(
            tcp.address(),
            tcp.port()
            );

    std::cout << "tcp: " << tcp << std::endl;
    std::cout << "udp: " << udp << std::endl;

    return 0;
}

sample invocation:

./a.out 
tcp: 127.0.0.1:123
udp: 127.0.0.1:123
Sam Miller