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

Boost: asio seems to define a separate endpoint class for each protocol, which is annoying if you want to perform both UDP and TCP operations on a specific endpoint (you have to convert from one to another). I always thought of the endpoint as an IP address (v4 or v6) and port number, regardless of TCP or UDP. Are there significant differences that justify individual classes? (i.e. both tcp :: socket and udp :: socket cannot accept something like ip :: endpoint?)

+6
boost-asio endpoints
source share
2 answers

Sockets are created differently.

socket(PF_INET, SOCK_STREAM) 

for TCP and

 socket(PF_INET, SOCK_DGRAM) 

for UDP.

I suspect this is the reason for the different types in Boost.Asio. See man 7 udp or man 7 tcp for more information. I assume Linux since you did not mark your question.

To solve your problem, extract the IP and port from the TCP endpoint and create an instance of the 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 call:

 ./a.out tcp: 127.0.0.1:123 udp: 127.0.0.1:123 
+4
source share

TCP and UDP ports are different. For example, two separate programs can listen on one port if one uses TCP and the other uses UDP. This is why endpoint classes are different.

+2
source share

All Articles