Interface for default route in Qt (on Linux)
Sometimes one needs to find out programmatically on which interface the default route is on. To do this in Qt, the following snippet can be used on Linux and probably other Unices (where everything’s a file ;)).
I used this snippet to prevent MediaTomb from listening on the wrong interface, but there are definitely other use cases as well:
QFile routeFile("/proc/net/route");
QString rc;
if (!routeFile.open(QFile::ReadOnly)) qWarn("Couldn't read routing information: %s", qPrintable(routeFile.errorString()));
QByteArray line;
while (!(line = routeFile.readLine()).isNull()) {
QList<QByteArray> parts = line.split('\t');
QByteArray intf = parts[0];
QByteArray route = parts[1];
QByteArray mask = parts[7];
// Find make sure the destination address is 0.0.0.0 and the netmask empty
if (route == "00000000" && mask == "00000000") {
rc = intf;
break;
}
}
return rc;
In the shell, you’d do something like this:
cut -f1,2,8 /proc/net/route --output-delimiter=:|grep 00000000:00000000$|cut -d: -f1