Is there a cross-platform way to get the local IP address (i.e. something that looks like 192.168.1.49
) of the computer using Qt?
I want to make an FTP server for a Symbian phone and I want to show the IP address the FTP client should connect to.
Use QNetworkInterface::allAddresses()
const QHostAddress &localhost = QHostAddress(QHostAddress::LocalHost);
for (const QHostAddress &address: QNetworkInterface::allAddresses()) {
if (address.protocol() == QAbstractSocket::IPv4Protocol && address != localhost)
qDebug() << address.toString();
}
QNetworkInterface::allAddresses()
will give you the network addresses. You can then filter the results to IPv4 addresses that are not loopback addresses:
QList<QHostAddress> list = QNetworkInterface::allAddresses();
for(int nIter=0; nIter<list.count(); nIter++)
{
if(!list[nIter].isLoopback())
if (list[nIter].protocol() == QAbstractSocket::IPv4Protocol )
qDebug() << list[nIter].toString();
}
If you require more information than just IP addresses (like the subnet), you have to iterate over all the interfaces.
QList<QNetworkInterface> allInterfaces = QNetworkInterface::allInterfaces();
QNetworkInterface eth;
foreach(eth, allInterfaces) {
QList<QNetworkAddressEntry> allEntries = eth.addressEntries();
QNetworkAddressEntry entry;
foreach (entry, allEntries) {
qDebug() << entry.ip().toString() << "/" << entry.netmask().toString();
}
}
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