Get local IP address in Qt
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();
}
QNetworkInterface returns lots of addresses. you must filter them, to get desirable result:
foreach (const QNetworkInterface &netInterface, QNetworkInterface::allInterfaces()) {
QNetworkInterface::InterfaceFlags flags = netInterface.flags();
if( (bool)(flags & QNetworkInterface::IsRunning) && !(bool)(flags & QNetworkInterface::IsLoopBack)){
foreach (const QNetworkAddressEntry &address, netInterface.addressEntries()) {
if(address.ip().protocol() == QAbstractSocket::IPv4Protocol)
qDebug() << address.ip().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();
}
}