I thought QHostAddress was it, but it strangely does not provide methods for validating whether or not the IP address is valid (anymore, got deprecated to Qt3).
Does anyone know?
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
I found all of the above solutions to be unreliable for IPv4 addresses at least. For example when '192' and '192.' were used to create a QHostAddress
. Both .setAddress() and if(QAbstractSocket::IPv4Protocol == address.protocol()
returned true
!
I found a more robust solution is to check the IP address string format using QRegularExpression
and QRegularExpressionValidator
.
An example of a good IPv4 regular expression can be found here
How to set Input Mask and QValidator to a QLineEdit at a time in Qt?
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