Search code examples
c++qtqt5ipv6ipv4

How to tell if QHostAddress is IPv4 or IPv6 in Qt5?


I can create a QHostAddress objects like this:

QHostAddress addr_ip4("127.0.0.1");
QHostAddress addr_ip6("::1/128");

And test their properties like this:

qDebug() << "addr_ip4.isNull() =      " << addr_ip4.isNull();
qDebug() << "addr_ip4.isLoopback() =  " << addr_ip4.isLoopback();
qDebug() << "addr_ip4.isMulticast() = " << addr_ip4.isMulticast();

qDebug() << "addr_ip6.isNull() =      " << addr_ip6.isNull();
qDebug() << "addr_ip6.isLoopback() =  " << addr_ip6.isLoopback();
qDebug() << "addr_ip6.isMulticast() = " << addr_ip6.isMulticast();

But... how can I tell which of the addresses are in fact IPv4 and which are IPv6?


Solution

  • Calling QHostAddress::protocol() will return a QAbstractSocket::NetworkLayerProtocol enum that specifies if the address is IPv4, IPv6, both, or other.