Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between tcp::endpoint and udp::endpoint in Boost::Asio?

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?)

like image 394
Michael Hardy Avatar asked Jul 23 '10 17:07

Michael Hardy


People also ask

What are some distinctions between UDP and tcp?

TCP is a connection-oriented protocol, whereas UDP is a connectionless protocol. A key difference between TCP and UDP is speed, as TCP is comparatively slower than UDP. Overall, UDP is a much faster, simpler, and efficient protocol, however, retransmission of lost data packets is only possible with TCP.

What is TCP endpoint?

TCP Endpoints come in two flavors: listening and connecting Endpoints. A listening TCP Endpoint accepts incoming connections over TCP (or TLS) from clients. A connecting TCP Endpoint establishes a connection over TCP (or TLS) to a server.

What is an endpoint in UDP?

UDP: a UDP endpoint is a combination of the IP address and the UDP port used, so different UDP ports on the same IP address are different UDP endpoints.


2 Answers

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
like image 141
Sam Miller Avatar answered Dec 28 '22 23:12

Sam Miller


TCP and UDP ports are different. For example, two separate programs can both listen on a single port as long as one uses TCP and the other uses UDP. This is why the endpoints classes are different.

like image 35
fabspro Avatar answered Dec 29 '22 00:12

fabspro