Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get local IP address in Qt

Tags:

c++

ip

qt

symbian

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.

like image 960
sashoalm Avatar asked Dec 12 '12 08:12

sashoalm


3 Answers

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();
}
like image 131
benjarobin Avatar answered Nov 17 '22 02:11

benjarobin


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();

  }
like image 17
Prasoon Avatar answered Nov 17 '22 01:11

Prasoon


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();
    }
}
like image 7
Dan Avatar answered Nov 17 '22 01:11

Dan