How to check Ethernet port connection status in Qt?

1.5k Views Asked by At

I am new to Qt .Actually, i want to check Whether the Ethernet is connected or not through qt application. For Example: when the Data is transfer from source to Destination through Ethernet. if i suddenly, remove the Ethernet cable my Qt application has to give some pop-up message like "the connection is unavailable". Is there any way to find this one? Finally,Sorry for my English.

2

There are 2 best solutions below

0
On

You might want to consider the Qt "Bearer Management" API:

http://doc.qt.io/qt-5/bearer-management.html

For example:

/ Set Internet Access Point
QNetworkConfigurationManager manager;
const bool canStartIAP = (manager.capabilities()
                          & QNetworkConfigurationManager::CanStartAndStopInterfaces);
// Is there default access point, use it
QNetworkConfiguration cfg = manager.defaultConfiguration();
if (!cfg.isValid() || (!canStartIAP && cfg.state() != QNetworkConfiguration::Active)) {
    QMessageBox::information(this, tr("Network"), tr(
                                 "No Access Point found."));
    return;
}
0
On

If you are on Linux, I found a nice idea somewhere to check with QT and QProcess if the Ethernet Cable is physically connected.

QProcess process;
QString sNetCableStatus = "";
process.start("sh", QStringList()<<"-c"<<"grep \"\" /sys/class/net/eth0/carrier");
process.waitForFinished();
sNetCableStatus = process.readAllStandardOutput();
if (sNetCableStatus.length() != 0)
{
    if (sNetCableStatus.left(1) == "1")
    {
        //connected
    }
    else if(sNetCableStatus.left(1) == "0")
    {
        //disconnected
    }
    else
    {
        //that should not happen
    }
}