defaultGatewayIp function
Returns the host machine's default-route gateway IP address.
Runs ip route and parses the line that starts with default to extract
the gateway address, e.g. 172.17.0.1. This is the address through which
a container inside a Docker bridge network can reach the host.
Returns null if:
- the
ipcommand is not available on the current platform, - the command exits with a non-zero status,
- no default route is present, or
- any other I/O error occurs.
Implementation
String? defaultGatewayIp() {
try {
final result = Process.runSync(
'sh',
['-c', "ip route|awk '/default/ { print \$3 }'"],
);
if (result.exitCode != 0) {
return null;
}
final ip = result.stdout.toString().trim();
return ip.isNotEmpty ? ip : null;
} catch (_) {
return null;
}
}