Skip to content

Read the Linux default gateways from the kernel routing table - #3853

Merged
dbwiddis merged 1 commit into
masterfrom
linux-default-gateway-from-proc
Oct 31, 2026
Merged

dbwiddis merged 1 commit into
masterfrom
linux-default-gateway-from-proc

Conversation

@dbwiddis

@dbwiddis dbwiddis commented Oct 31, 2026 •

Copy link
Copy Markdown
Member

Problem

On Linux, NetworkParams.getIpv4DefaultGateway() and getIpv6DefaultGateway() ran route -A inet -n and route -A inet6 -n. route lives in /usr/sbin, which is not on a normal user's PATH on Debian 13, and net-tools is not installed at all on many current distributions. Both methods then return "". Found during the s390x survey on cfarm191 (Debian 13, net-tools installed), where ip route reported default via 148.100.74.1 and OSHI reported nothing. This is not specific to s390x.

Fix

  • Both methods now select from the routes RouteTable already parses from /proc/net/route and /proc/net/ipv6_route (the same source as getRoutes()): the next hop of the default route (prefix length 0) with the lowest metric, which is the choice the route-based code made. A default route with no next hop, such as the kernel's unreachable ::/0 on lo, is ignored.
  • The shared code covers JNA, FFM and native-free alike, and saves two process spawns per call.
  • IPv6 text keeps the compressed form route printed (fe80::4a2e:72ff:fe54:5e9f): the compression regex moves out of parseUtAddrV6toIP into a new ParseUtil.formatIpAddress(byte[]), which parseUtAddrV6toIP now calls, so its output is unchanged.

Tests

  • LinuxNetworkParamsTest: gateway selection over route lists modelled on cfarm191's real IPv4 and IPv6 tables, including a higher-metric default route listed first and a gateway-less ::/0; the empty cases. The class-level @EnabledOnOs(OS.LINUX) moved onto the one test that reads /proc, so these run on every CI platform.
  • ParseUtilTest: formatIpAddress for IPv4, IPv6 (including longest-zero-run compression) and an invalid length.

Verification

  • Locally: gate and clean install -Perror-prone.
  • On cfarm191 (s390x, on master with Decode /proc/net addresses in the host's byte order on Linux #3852): gateways went from "" to 148.100.74.1 and fe80::4a2e:72ff:fe54:5e9f, matching ip route show default and ip -6 route show default. NativeComparisonTest and NativeFreeComparisonTest networkParams() pass there.

Summary by CodeRabbit

  • Bug Fixes
    • Linux default gateway detection now reads the kernel routing table, so gateway addresses can be retrieved even when the route command is unavailable.
    • When multiple default routes are available, the gateway with the lowest metric is selected. Routes without a usable next-hop address are ignored.
  • New Features
    • Added IP address formatting for IPv4 and IPv6 addresses, including compressed IPv6 notation. Invalid address data returns an unknown value.

getIpv4DefaultGateway() and getIpv6DefaultGateway() ran `route -A inet[6] -n`.
route is in /usr/sbin, which a normal user's PATH does not include on Debian
13, and net-tools is absent altogether on many current distributions, so both
returned "". Measured on cfarm191 (Debian 13) with net-tools installed.

Select the gateway instead from the routes RouteTable already parses from
/proc/net/route and /proc/net/ipv6_route: the next hop of the default route
with the lowest metric, the same choice the route-based code made. This also
saves two process spawns per call. The IPv6 compression that kept the text in
route's form moves out of parseUtAddrV6toIP into ParseUtil.formatIpAddress,
which both now use.
@coderabbitai

coderabbitai Bot commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review.

Recent review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: eb4f0d08-384f-411d-a93f-3730f7c687b8
Commits

Reviewing files that changed from the base of the PR and between 5154264 and d65fde5.

Files selected for processing: 5
  • CHANGELOG.md
  • oshi-common/src/main/java/oshi/software/common/os/linux/LinuxNetworkParams.java
  • oshi-common/src/main/java/oshi/util/ParseUtil.java
  • oshi-common/src/test/java/oshi/software/common/os/linux/LinuxNetworkParamsTest.java
  • oshi-common/src/test/java/oshi/util/ParseUtilTest.java

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 6 remain after this review.

Recent review details
Context from checks skipped due to timeout: 16
  • GitHub Check: Test JDK 25, OpenIndiana
  • GitHub Check: Test JDK 25, NetBSD
  • GitHub Check: Test JDK 25, OpenBSD
  • GitHub Check: Test JDK 25, FreeBSD
  • GitHub Check: Test JDK 25, DragonFly BSD
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 25, ubuntu-latest
  • GitHub Check: Test JDK 26, ubuntu-latest
  • GitHub Check: Test JDK 25, macos-latest
  • GitHub Check: Error Prone
  • GitHub Check: Lint (Spotless, Checkstyle)
  • GitHub Check: Test JDK 25, windows-latest
  • GitHub Check: Test JDK 21, ubuntu-latest
  • GitHub Check: Lint (ForbiddenAPIs, Javadoc, SLF4J)
  • GitHub Check: Analyze (java)
  • GitHub Check: Analyze (java-kotlin)
Additional context used
Code guidelines: 2
AGENTS.md — auto-discovered
.github/CONTRIBUTING.md — auto-discovered
Path-based instructions: 8
Source excerpt: **Language level.**

CodeRabbit inference engine (AGENTS.md)

Files:

  • oshi-common/src/main/java/oshi/util/ParseUtil.java
  • oshi-common/src/main/java/oshi/software/common/os/linux/LinuxNetworkParams.java
Source excerpt: **Banned APIs** (`config/forbidden-apis.txt` and friends, enforced by `forbiddenapis:check`): `oshi-common` may not reference `com.sun.jna.**`, `java.lang.foreign.**`, or any `System.load`/`loadLibrary`.

CodeRabbit inference engine (AGENTS.md)

Files:

  • oshi-common/src/test/java/oshi/util/ParseUtilTest.java
  • oshi-common/src/main/java/oshi/util/ParseUtil.java
  • oshi-common/src/test/java/oshi/software/common/os/linux/LinuxNetworkParamsTest.java
  • oshi-common/src/main/java/oshi/software/common/os/linux/LinuxNetworkParams.java
Source excerpt: **Banned APIs** (`config/forbidden-apis.txt` and friends, enforced by `forbiddenapis:check`): `Integer.parseInt`, `Long.parseLong`, `Double.parseDouble`, `Integer.decode`, and relatives are banned.

CodeRabbit inference engine (AGENTS.md)

Files:

  • oshi-common/src/main/java/oshi/util/ParseUtil.java
  • oshi-common/src/main/java/oshi/software/common/os/linux/LinuxNetworkParams.java
Source excerpt: **Their `src/test` compiles at `release 17`**, set by `maven.compiler.testRelease` in the root `pom.xml`.

CodeRabbit inference engine (AGENTS.md)

Files:

  • oshi-common/src/test/java/oshi/util/ParseUtilTest.java
  • oshi-common/src/test/java/oshi/software/common/os/linux/LinuxNetworkParamsTest.java
Source excerpt: Text blocks strip incidental leading and trailing whitespace, and spotless applies `trimTrailingWhitespace` to Java sources, so a fixture whose real output carries trailing spaces or tab alignment needs explicit `\s` or `\t`...

CodeRabbit inference engine (AGENTS.md)

Files:

  • oshi-common/src/test/java/oshi/util/ParseUtilTest.java
  • oshi-common/src/main/java/oshi/util/ParseUtil.java
  • oshi-common/src/test/java/oshi/software/common/os/linux/LinuxNetworkParamsTest.java
  • oshi-common/src/main/java/oshi/software/common/os/linux/LinuxNetworkParams.java
Source excerpt: **Adding a test in a package that no existing test uses means adding a line to that module's `module-info.test`:**

CodeRabbit inference engine (AGENTS.md)

Files:

  • oshi-common/src/test/java/oshi/util/ParseUtilTest.java
  • oshi-common/src/test/java/oshi/software/common/os/linux/LinuxNetworkParamsTest.java
Applicability reference: AGENTS.md: # AGENTS.md Instructions for AI coding agents working in the OSHI repository.

CodeRabbit inference engine (.github/CONTRIBUTING.md)

Files:

  • CHANGELOG.md
Source excerpt: An entry is one bullet, on **one line however long it runs** — the longest in the file is over a thousand characters.

CodeRabbit inference engine (AGENTS.md)

Files:

  • CHANGELOG.md
Additional comments: 5
oshi-common/src/main/java/oshi/util/ParseUtil.java: 1

1384-1395: LGTM!

Also applies to: 1397-1397

oshi-common/src/test/java/oshi/util/ParseUtilTest.java: 1

836-848: LGTM!

oshi-common/src/main/java/oshi/software/common/os/linux/LinuxNetworkParams.java: 1

8-8: LGTM!

Also applies to: 46-46, 51-51, 54-65, 69-69

oshi-common/src/test/java/oshi/software/common/os/linux/LinuxNetworkParamsTest.java: 1

16-17: LGTM!

Also applies to: 23-24, 38-38, 45-84

CHANGELOG.md: 1

9-9: LGTM!

Walkthrough

Linux gateway methods now query the kernel routing table and select a qualifying default route. A shared public helper formats IP addresses from byte arrays. Tests cover gateway selection and address formatting.

Changes: Linux gateway lookup

Layer / File(s) Summary
IP address formatting
oshi-common/src/main/java/oshi/util/ParseUtil.java, oshi-common/src/test/java/oshi/util/ParseUtilTest.java
ParseUtil.formatIpAddress formats byte arrays as IP addresses and returns Constants.UNKNOWN if address construction fails. parseUtAddrV6toIP uses the helper. Tests cover IPv4, IPv6, zero-group compression, and an invalid-length input.
Route-based gateway selection
oshi-common/src/main/java/oshi/software/common/os/linux/LinuxNetworkParams.java, oshi-common/src/test/java/oshi/software/common/os/linux/LinuxNetworkParamsTest.java, CHANGELOG.md
The IPv4 and IPv6 gateway methods query RouteTable. A shared selector chooses a qualifying default route with the lowest metric, or returns an empty string when none qualifies. Tests cover route selection and missing next hops. The changelog records the change.

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix · Severity of issue fixed: Low

Sequence Diagram(s)

sequenceDiagram
  participant LinuxNetworkParams
  participant RouteTable
  participant GatewaySelector
  participant ParseUtil
  LinuxNetworkParams->>RouteTable: Query routes
  RouteTable-->>LinuxNetworkParams: Return routes
  LinuxNetworkParams->>GatewaySelector: Select qualifying default route
  GatewaySelector->>ParseUtil: Format gateway address
  ParseUtil-->>LinuxNetworkParams: Return formatted address
Loading

Possibly related PRs

  • oshi/oshi#3852: Changes IPv4 route address decoding used by the RouteTable results that this PR examines.
Merge Risk: Minimal · up to d65fd

No merge-blocking risk was identified in the route-based gateway lookup.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 75.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documenta… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly and concisely describes the main change: reading Linux default gateways from the kernel routing table.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Docstring Coverage

Explanation

Docstring coverage is 75.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 4 functions across 4 files. (1 skipped: 1 unsupported.)

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

Finishing Touches
Generate docstrings
  • Commit to this branch
  • Create a new PR
Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

A rabbit checks the routes at dawn,
And finds the gateway, neatly drawn.
The bytes take shape in v4 and v6,
With zero groups compressed with tricks.
If no next hop is there to see,
An empty string is returned free.

@dbwiddis
dbwiddis merged commit c55f2d4 into master Oct 31, 2026
22 of 23 checks passed
@dbwiddis
dbwiddis deleted the linux-default-gateway-from-proc branch October 31, 2026 05:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant