2023-09-26 16:26:15 +08:00
|
|
|
#include "netif.h"
|
|
|
|
|
#include "common/io/io.h"
|
|
|
|
|
|
2023-09-26 21:49:01 +08:00
|
|
|
#include <net/if.h>
|
2023-09-26 16:26:15 +08:00
|
|
|
#include <stdio.h>
|
|
|
|
|
|
2023-09-26 21:49:01 +08:00
|
|
|
#define FF_STR_INDIR(x) #x
|
|
|
|
|
#define FF_STR(x) FF_STR_INDIR(x)
|
|
|
|
|
|
2025-04-01 10:48:30 +08:00
|
|
|
static bool getDefaultRouteIPv4(char iface[IF_NAMESIZE + 1], uint32_t* ifIndex)
|
2023-09-26 16:26:15 +08:00
|
|
|
{
|
|
|
|
|
FILE* FF_AUTO_CLOSE_FILE netRoute = fopen("/proc/net/route", "r");
|
|
|
|
|
if (!netRoute) return false;
|
|
|
|
|
|
2024-10-13 21:32:09 +08:00
|
|
|
// skip first line
|
2024-10-14 12:30:39 +08:00
|
|
|
FF_UNUSED(fscanf(netRoute, "%*[^\n]\n"));
|
2023-09-26 16:26:15 +08:00
|
|
|
|
2025-04-01 10:48:30 +08:00
|
|
|
unsigned long long destination; //, gateway, flags, refCount, use, metric, mask, mtu, ...
|
2023-09-26 21:49:01 +08:00
|
|
|
while (fscanf(netRoute, "%" FF_STR(IF_NAMESIZE) "s%llx%*[^\n]", iface, &destination) == 2)
|
2023-09-26 16:26:15 +08:00
|
|
|
{
|
|
|
|
|
if (destination != 0) continue;
|
2023-09-27 10:13:59 +08:00
|
|
|
*ifIndex = if_nametoindex(iface);
|
2023-09-26 16:26:15 +08:00
|
|
|
return true;
|
|
|
|
|
}
|
2025-04-01 10:48:30 +08:00
|
|
|
iface[0] = '\0';
|
2023-09-26 16:26:15 +08:00
|
|
|
return false;
|
|
|
|
|
}
|
2025-04-01 10:48:30 +08:00
|
|
|
|
|
|
|
|
static bool getDefaultRouteIPv6(char iface[IF_NAMESIZE + 1], uint32_t* ifIndex)
|
|
|
|
|
{
|
|
|
|
|
FILE* FF_AUTO_CLOSE_FILE netRoute = fopen("/proc/net/ipv6_route", "r");
|
|
|
|
|
if (!netRoute) return false;
|
|
|
|
|
|
|
|
|
|
uint32_t prefixLen;
|
|
|
|
|
//destination, dest_prefix_len, source, src_prefix_len, next hop, metric, ref counter, use counter, flags, iface
|
|
|
|
|
while (fscanf(netRoute, "%*s %x %*s %*s %*s %*s %*s %*s %*s %" FF_STR(IF_NAMESIZE) "s", &prefixLen, iface) == 2)
|
|
|
|
|
{
|
|
|
|
|
if (prefixLen != 0) continue;
|
|
|
|
|
*ifIndex = if_nametoindex(iface);
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
iface[0] = '\0';
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
bool ffNetifGetDefaultRouteImpl(char iface[IF_NAMESIZE + 1], uint32_t* ifIndex)
|
|
|
|
|
{
|
|
|
|
|
if (getDefaultRouteIPv4(iface, ifIndex))
|
|
|
|
|
return true;
|
|
|
|
|
|
|
|
|
|
return getDefaultRouteIPv6(iface, ifIndex);
|
|
|
|
|
}
|