Aug 21, 2015

Detecting if Windows computer has started network after boot in C++

I just found a customers computer that after boot started our Windows service before network had started properly. Which caused gethostbyname("HOSTNAME") to return 127.0.0.1. So we opened a server on the wrong interface, clients could not connect.

After a while I found a way to enumerate the network-interfaces to see if any non-loopback existed...
When testing we found that after checking+sleeping for 3 seconds the network appeared again.

bool HasAnyNonLookbackInterfaceGetIpAddressesOrdered()
{
    ULONG size=0;
    GetIpAddrTable(NULL, &size, FALSE);

    std::auto_ptr<MIB_IPADDRTABLE> tab(new MIB_IPADDRTABLE[size/sizeof(MIB_IPADDRTABLE)+1]);

    DWORD res = GetIpAddrTable(tab.get(), &size, FALSE);
    if ( res != NO_ERROR )
        return false;



    std::list<unsigned long> addrlist;// ordered
    for ( unsigned i=0; i<tab->dwNumEntries; i++ )
    {
        MIB_IFROW ifaceInfo;
        ZeroMemory(&ifaceInfo, sizeof(ifaceInfo));
        ifaceInfo.dwIndex = tab->table[i].dwIndex;

        res = GetIfEntry( &ifaceInfo );
        if ( res != NO_ERROR )
            return false;

        if ( ifaceInfo.dwType != MIB_IF_TYPE_LOOPBACK )
            return true;
    } 
    
    return false;
}

Another possiblity, it is a Windows Service is to add a dependency on the service LanmanServer...