I am using boost::asio::ip::tcp. Once connection is established between my TCP client and TCP server, I want to get the local_endpoint's address as string, and the remote_endpoint's address as string on both sides.
auto localAddress = tcpSocket.local_endpoint().address().to_string();
auto remoteAddress = tcpSocket-remote_endpoint().address().to_string();
But I am confused. In some cases I get 127.0.0.1 and in some cases I get ::ffff:127.0.0.1. Is ::ffff:127.0.0.1 V6 and 127.0.0.1 is V4? I just need the IP address that is 127.0.0.1.
I can do a substring extraction to get the 127.0.0.1 piece as well. But I want to know if there a boost::asio standard technique to extract/convert ::ffff:127.0.0.1 to 127.0.0.1?
ip::address stores either IPv4 or IPv6 address. You can check what kind of address is stored by is_v6() or is_v4() methods.
Addresses of IPv6 are much more than IPv4, so only some subset of IPv6 addresses can be mapped into IPv4.
When you have IPv6 you could use is_v4_mapped method to check this map ip6 -> ip4 is possible. If so, just use operator<< overload to extract IPv4 in string format:
Example code:
boost::asio::ip::address addr{boost::asio::ip::make_address("::ffff:127.0.0.1")};
if (addr.is_v6())
{
boost::asio::ip::address_v6 ipv6 = addr.to_v6();
if (ipv6.is_v4_mapped())
{
auto ipv4 = ipv6.to_v4();
std::ostringstream os;
os << ipv4;
std::string str = os.str(); // 127.0.0.1
std::cout << str << std::endl;
}
}
Live demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With