Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Qt provide a class that represents an IP address?

Tags:

qt

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?

like image 510
sivabudh Avatar asked Feb 10 '10 21:02

sivabudh


4 Answers

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.

like image 52
RA. Avatar answered Oct 22 '22 13:10

RA.


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

like image 29
sivabudh Avatar answered Oct 22 '22 12:10

sivabudh


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

like image 23
rolevax Avatar answered Oct 22 '22 11:10

rolevax


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?

like image 1
PeterCAN76 Avatar answered Oct 22 '22 12:10

PeterCAN76