Does Qt provide a class that represents an IP address?

There is an alternative to using isIpv4Address() and isIPv6Address(). For example:

QHostAddress address(myString);
if (QAbstractSocket::IPv4Protocol == address.protocol())
{
   qDebug("Valid IPv4 address.");
}
else if (QAbstractSocket::IPv6Protocol == address.protocol())
{
   qDebug("Valid IPv6 address.");
}
else
{
   qDebug("Unknown or invalid address.");
}

See also:

http://doc.qt.digia.com/4.6/qhostaddress.html#protocol

Hope this helps.


Here is the official answer from Nokia support engineer, name removed for privacy protection:

I posted a question on stackoverflow.com as follow:

Does Qt provide a class that represents an IP address?

You can see that someone posted a solution to my question already.

However, I want to ask how come Nokia doesn't just provide a method to

QHostAddress ( like isValid() ) that will check the host address's validity?

Thank you for your inquiry. You can use the isNull() method to check the validity. It will return true for invalid addresses: http://doc.qt.digia.com/4.6/qhostaddress.html#isNull

Hope this helps.

Regards,

Support Engineer, Qt Development Frameworks, Nokia


The bool return value of QHostAddress::setAddress(const QString &address) tells if the string is successfully parsed as an IPv4 or IPv6 address.

QHostAddress addr;
if (addr.setAddress(myString)) {
    // valid
} else {
    // invalid
}

http://doc.qt.io/qt-5/qhostaddress.html#setAddress-5

Tags:

Qt