A
A
anikavoi2016-11-15 02:41:35
Qt
anikavoi, 2016-11-15 02:41:35

How to get default gateway?

I needed a function that returns the ip of the default gateway.
After a lot of googling this came up:

#include <QtNetwork>
#include "Iphlpapi.h"

............

QString getDefaultGateway(void)
{
    union unIPAddr {
        struct  {
            unsigned char p1;
            unsigned char p2;
            unsigned char p3;
            unsigned char p4;
        } bIPAddr;
        DWORD dwIPAddr;
    };

    MIB_IPFORWARDROW BestRoute;

    DWORD dwResult = GetBestRoute(inet_addr("0.0.0.0"), 0, &BestRoute);

    unIPAddr IPAddrF;
    IPAddrF.dwIPAddr = BestRoute.dwForwardNextHop;
    QString qsDGWIp = QString::number(IPAddrF.bIPAddr.p1) + "." +  QString::number(IPAddrF.bIPAddr.p2) + "." + QString::number(IPAddrF.bIPAddr.p3) + "." + QString::number(IPAddrF.bIPAddr.p4) ;

    return qsDGWIp;
}

(requires "LIBS += -liphlpapi" in .pro)
It works, but I really don't like it.
Does anyone know a more correct and beautiful way?
PS: And yes - there can be more than one default gateway :(
PPS: If there is a solution for linux, I will also be very grateful

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question