Netif (Windows): correct default route detection (v2)

This commit is contained in:
李通洲
2025-07-24 19:31:01 +08:00
parent a90e1d7ccf
commit 02c3254961
3 changed files with 30 additions and 12 deletions
+2 -1
View File
@@ -3,7 +3,8 @@
#ifndef _WIN32
#include <net/if.h>
#else
#define IF_NAMESIZE 0
#include <ws2tcpip.h>
#include <iphlpapi.h>
#endif
bool ffNetifGetDefaultRouteImpl(char iface[IF_NAMESIZE + 1], uint32_t* ifIndex);
-3
View File
@@ -2,8 +2,5 @@
#include "fastfetch.h"
#ifndef _WIN32
const char* ffNetifGetDefaultRouteIfName();
#endif
uint32_t ffNetifGetDefaultRouteIfIndex();
+28 -8
View File
@@ -4,31 +4,51 @@
#include <ws2tcpip.h> // AF_INET6, IN6_IS_ADDR_UNSPECIFIED
#include <iphlpapi.h>
bool ffNetifGetDefaultRouteImpl(FF_MAYBE_UNUSED char iface[IF_NAMESIZE + 1], uint32_t* ifIndex)
bool ffNetifGetDefaultRouteImpl(char iface[IF_NAMESIZE + 1], uint32_t* ifIndex)
{
PMIB_IPFORWARD_TABLE2 pIpForwardTable = NULL;
DWORD result = GetIpForwardTable2(AF_UNSPEC, &pIpForwardTable);
if (result != NO_ERROR)
if (!NETIO_SUCCESS(GetIpForwardTable2(AF_UNSPEC, &pIpForwardTable)))
return false;
bool foundDefault = false;
uint32_t smallestMetric = UINT32_MAX;
for (ULONG i = 0; i < pIpForwardTable->NumEntries; ++i)
{
MIB_IPFORWARD_ROW2* row = &pIpForwardTable->Table[i];
if (row->Age > row->ValidLifetime) continue;
if ((row->DestinationPrefix.PrefixLength == 0) &&
((row->DestinationPrefix.Prefix.Ipv4.sin_family == AF_INET &&
row->DestinationPrefix.Prefix.Ipv4.sin_addr.S_un.S_addr == 0) ||
(row->DestinationPrefix.Prefix.Ipv6.sin6_family == AF_INET6 &&
IN6_IS_ADDR_UNSPECIFIED(&row->DestinationPrefix.Prefix.Ipv6.sin6_addr))))
{
*ifIndex = row->InterfaceIndex;
foundDefault = true;
break;
MIB_IF_ROW2 ifRow = {
.InterfaceIndex = row->InterfaceIndex,
};
if (NETIO_SUCCESS(GetIfEntry2(&ifRow)) &&
ifRow.OperStatus == IfOperStatusUp)
{
MIB_IPINTERFACE_ROW ipInterfaceRow = {
.Family = (row->DestinationPrefix.Prefix.Ipv4.sin_family == AF_INET) ? AF_INET : AF_INET6,
.InterfaceIndex = row->InterfaceIndex,
};
uint32_t realMetric = row->Metric /* Metric offset */;
if (NETIO_SUCCESS(GetIpInterfaceEntry(&ipInterfaceRow)))
realMetric += ipInterfaceRow.Metric /* Interface metric */;
if (realMetric < smallestMetric)
{
smallestMetric = realMetric;
*ifIndex = row->InterfaceIndex;
if (WideCharToMultiByte(CP_UTF8, 0, ifRow.Alias, -1, iface, IF_NAMESIZE, NULL, NULL) > 0)
iface[IF_NAMESIZE] = '\0';
foundDefault = true;
}
}
}
}