Skip to content
al8nPublic

About

Cross-platform enumeration of network interfaces and their MTU, gateway, multicast, and local/private/public IP addresses — with a libc-free netlink backend on Linux and no getifaddrs dependency.

Topics

Resources

Contributing

Security policy

Stars

27 stars

Watchers

1 watching

Forks

Repository files navigation

GetIfs

Cross-platform network interface, MTU, gateway, multicast, and local/private/public IP address enumeration, with a libc-free netlink backend on Linux and no getifaddrs dependency.

github LoC Build codecov

docs.rs crates.io crates.io license

Installation

[dependencies]
getifs = "0.8"

The minimum supported Rust version is 1.85; see Maintenance for the smol_str resolver note.

Highlights

  • Interfaces and addresses: enumerate interfaces with their MTU and flags, local/private/public IP addresses, and multicast group memberships.
  • Gateways and routing table: discover IPv4 and IPv6 gateway addresses and enumerate kernel routing-table entries.
  • Default interfaces and preferred addresses (new in 0.8): family-aware default-route interfaces, and a preferred public or private address that is Ok(None) rather than an error when none is eligible.
  • Cached snapshots (new in 0.8): InterfaceSnapshot with composable predicates and comparators, so repeated filtering and ordering performs no OS I/O.
  • Complete hardware addresses (new in 0.8): six-byte MAC, eight-byte EUI-64, twenty-byte InfiniBand, and exact raw bytes for any other nonzero width.
  • Checked IP and subnet math (new in 0.8): checked address offsets, usable-host indexing, and subnet offsets.
  • RFC-based classification: filter addresses by RFC classification, with public_* and private_* queries built on the RFC 6890 special-purpose registries.
  • Libc-free on Linux: zero libc dependency, using netlink directly.
  • Cross-platform: Linux, macOS, BSD, Windows, and Android; see Platform support.
  • High performance: up to 72x faster than alternatives on macOS; see Performance.

Quick start

Enumerate interfaces, local IP addresses, and gateways:

use getifs::{interfaces, local_addrs, gateway_addrs};

// Get all network interfaces
let interfaces = interfaces()?;
for interface in interfaces {
    println!("Interface: {} (index: {})", interface.name(), interface.index());
    println!("  MTU: {}", interface.mtu());
    println!("  Flags: {:?}", interface.flags());
}

// Get local IP addresses
let local_ips = local_addrs()?;
for ip in local_ips {
    println!("Local IP: {}", ip);
}

// Get gateway addresses
let gateways = gateway_addrs()?;
for gateway in gateways {
    println!("Gateway: {}", gateway);
}

Pick an address to advertise

Ask for one preferred private address and list the default-route interfaces of each family. Both calls succeed on a host that has no eligible address or no default route; they report None or an empty slice instead.

use getifs::{default_interfaces, preferred_private_addr};

// `None` means no eligible private address was captured.
match preferred_private_addr()? {
    Some(net) => println!("Advertise {} (interface index {})", net.addr(), net.index()),
    None => println!("No eligible private address"),
}

// IPv4 and IPv6 are reported separately; either slice can be empty.
let defaults = default_interfaces()?;
for (family, interfaces) in [("IPv4", defaults.ipv4()), ("IPv6", defaults.ipv6())] {
    if interfaces.is_empty() {
        println!("No {family} default interface");
    }
    for interface in interfaces {
        println!("{family} default: {} (index {})", interface.name(), interface.index());
    }
}

Examples

Run any of them with cargo run --example <name>.

Basics

Example Shows
examples/interfaces.rs Fetching all interfaces
examples/addrs.rs Fetching all interface addresses (excluding multicast addrs)
examples/multicast_addrs.rs Fetching all interface multicast addresses
examples/gateway.rs Fetching gateway addresses
examples/route.rs Fetching the routing table
examples/local_ip_addrs.rs Fetching local ip addresses
examples/filter_by_rfc.rs Fetching ip addresses by RFC
examples/snapshot_query.rs Querying a cached snapshot with typed predicates and ordering
examples/preferred_addrs.rs Selecting public/private preferred addresses without requiring one
examples/default_interfaces.rs Listing family-aware default-route interfaces
examples/checked_ip_math.rs Exploring checked synthetic IP-address and subnet arithmetic
examples/hardware_addresses.rs Inspecting captured and synthetic hardware-address forms

Platform support

Capabilities

Platform Interfaces, unicast addresses, and local MTU Gateways and routes Multicast memberships
Linux Yes Yes Yes
Android Yes* Yes Unsupported
Apple platforms Yes Yes Yes
FreeBSD Yes Yes Yes
NetBSD / OpenBSD Yes Yes Unsupported
DragonFly Yes Yes Unsupported
Windows Yes Yes Yes

* Android's untrusted-app fallback can enumerate only interfaces with at least one current address; see Android.

Backends

OS Approach
Linux (no libc) socket(AF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, NETLINK_ROUTE)
Android (no libc) netlink with kernel auto-bind + SIOCGIF* ioctl fallback — see Android
BSD-like sysctl
Windows IP Helper: GetIfTable2Ex / GetIfEntry2 (interfaces), GetAdaptersAddresses (addresses), routing tables (routes, gateways)

Guide

The APIs in this guide are new in 0.8.

Snapshots and predicates

InterfaceSnapshot::capture() stores one interface collection and one unicast-address collection. Its iterators borrow both collections, so repeated filtering and ordering performs no OS I/O and does not clone interface names or hardware bytes. Addresses whose interface is missing from the capture stay visible through snapshot.networks() but are omitted from joined iteration.

use getifs::{
    order, predicate, Flags, InterfaceAddressIteratorExt, InterfaceSnapshot,
};

let snapshot = InterfaceSnapshot::capture()?;
let up = snapshot.matching(predicate::flags(Flags::UP));
let ordered = up.sorted_with(&order::by_interface_index());
assert!(ordered.iter().all(|record| record.interface().flags().contains(Flags::UP)));
  • predicate::name, predicate::cidr, predicate::rfc, and predicate::flags are typed constructors.
  • Any Rust closure accepting an InterfaceAddress is also an InterfacePredicate; .and(), .or(), and .not() short-circuit.
  • AddressComparator provides .then() and .reverse(), and the order module provides default-route, interface-up, family, network, index, address, and cached-name comparators.
  • Comparators use captured fields only and never resolve an interface name or query routes.

Default interfaces

default_interfaces() returns separate IPv4 and IPv6 slices, read with ipv4() and ipv6():

  • A family can have no default route, and equal-best routes remain in the corresponding slice.
  • The same interface can appear in both families.
  • The route and interface captures are weak snapshots, so an index that vanishes or has no UTF-8 name is simply absent from the joined slice.
  • Link-local-only interfaces are still represented because this API starts from unfiltered interfaces, not from local address results.
  • A missing route or unavailable address-family stack yields an empty family slice; permission, malformed-response, and persistent-interrupt errors still propagate.

Which route wins depends on the platform:

  • Linux follows the built-in rule chain of each family (IPv4 local, main, default; IPv6 local, main) with metric and IPv6 router-preference ordering:
    • A winning default route of any type other than unicast, local, or throw (blackhole, unreachable, prohibit, and others such as nat or broadcast) means no default interface.
    • throw falls through to the next built-in table.
    • An expired route, or a default route or multipath leg whose nexthop is dead, link-down, or unresolved, is skipped.
    • An IPv4 route through a nexthop object with no usable leg instead ends its table's lookup, so the next built-in table decides, while IPv6 moves on to the next route.
    • Custom ip rule policy tables are not modeled.
  • Windows skips disconnected interfaces and interfaces that set DisableDefaultRoutes.
  • BSD: OpenBSD uses route priority; other BSD targets cannot expose an equivalent priority, so they retain every usable default as equal-best.
  • Apple platforms: the interface-scoped defaults that Apple platforms install for non-primary interfaces are not default routes.
  • All platforms: a default route is a /0 route, so split-default halves such as 0.0.0.0/1 and ::/1 are not default routes.

Selection reads only the routing table: it honours a route's own state (dead, link-down) but never consults the neighbor table, so it does not reproduce IPv6 router reachability checks on non-forwarding Linux hosts or IPv4 dead-gateway detection among equal-metric defaults. Equal-best routes are reported whole, where the kernel picks one per lookup, so the result can be a superset of the routes in use. For IPv6, a higher-preference or lower-metric default whose router is currently unreachable still ranks first: it can be ranked above a reachable default or reported alongside one, and the result can name only the unreachable router's interface. The result is a static snapshot that does not follow neighbor-state changes, while the kernel's choice can differ from one lookup to the next.

Preferred addresses

preferred_public_*_addr and preferred_private_*_addr return one typed candidate.

Eligibility:

  • The interface must have Flags::UP.
  • Every forwarding-blacklisted address is excluded before public/private classification and ranking.
  • Address lifetime and duplicate-address-detection state are not inspected, so a tentative, deprecated, or duplicate IPv6 address remains eligible.
  • A default route is a preference, not an eligibility requirement, so an eligible address can still be selected when that family has no default route.
  • _by variants replace only the ranking; they cannot make down or nonforwardable candidates eligible.

The mixed-family default ranking, in order:

  1. Family-default membership.
  2. IPv4 before IPv6.
  3. Larger network (smaller prefix).
  4. Lower interface index.
  5. Numeric address.
  6. Cached interface name.

A complete tie keeps the first captured record. Because default membership comes first, an eligible IPv6 default candidate outranks an eligible nondefault IPv4 candidate; the family-specific selectors consider only their own family, so the IPv4-before-IPv6 tie-break is irrelevant there.

Ok(None) means no eligible joined record was captured; ordinary enumeration, permission, and route-parsing errors remain Err.

Hardware addresses

Interface::hardware_addr() returns a HardwareAddr: six-byte Mac, eight-byte Eui64, twenty-byte InfiniBand, or exact Raw bytes for any other nonzero width. Interface::mac_addr() remains available for ordinary six-byte MAC callers and is const-compatible. Empty and all-zero hardware values normalize to None. This intentionally changes Windows and BSD 0.8 behavior: their previously exposed all-zero MAC values now become absent.

HardwareAddr equality and hashing use the full byte sequence and length, so for example Raw six-byte data compares equal to the corresponding Mac. Because Interface derives equality and hashing over its captured snapshot, arbitrary hardware bytes participate in its identity as well.

Checked IP math

CheckedIpAddrExt offers checked addition and subtraction for Ipv4Addr, Ipv6Addr, and IpAddr. UsableIpNetExt provides usable-host indexing:

  • IPv4 /0 through /30 exclude network and broadcast.
  • /31 includes both endpoints.
  • /32 has its one address.
  • IPv6 includes every address in its prefix.
  • All usable-host offsets remain within the original prefix.

CheckedIpNetExt offsets Ipv4Net, Ipv6Net, and IpNet without changing the prefix. Address offsets can cross a subnet; whole-subnet offsets preserve the stored host bits. /0 accepts only a zero whole-subnet offset, while /32 and /128 have a one-address stride. No arithmetic is added to IfNet, so a computed value never implies an address assignment on an interface.

use getifs::{CheckedIpNetExt, ipnet::Ipv4Net};

let net: Ipv4Net = "192.0.2.42/24".parse()?;
assert_eq!(net.checked_add_subnets(1).unwrap().addr().to_string(), "192.0.3.42");
# Ok::<(), Box<dyn std::error::Error>>(())

API contract

  • public_* means not in the RFC 6890 special-purpose registries. private_* is the longstanding local-use classification: RFC 6890 ranges that are not in its forwarding blacklist. It includes RFC 1918, CGNAT, and IPv6 ULA, and excludes documentation, loopback, and link-local ranges; it is not a synonym for RFC 1918 alone. Classification follows the IANA snapshot in the resolved compatible iprfc 1.x release, not an immutable snapshot tied to a getifs release.
  • get_interface_mtu and get_ifaddr_mtu return a local link MTU, not a remote path MTU. IP-only MTU lookup returns NotFound for no local match and InvalidInput for an address assigned to distinct interfaces. IPv6 link-local addresses should be queried with their IfAddr scope.
  • interface_by_index and interface_by_name return Ok(None) when the index or name is absent from the interface enumeration (including an interface skipped for an unrepresentable name) or the OS reports a known missing-interface status. Permission, parsing, and other system errors remain errors. The older ifname_to_v6_iface and ifname_to_iface retain their historical Option meanings; a missing name remains an error there.
  • Kernel reads are weak snapshots, not transactions. An interface, address, name, or index can change between calls (or during a multi-query operation), so callers must handle ordinary TOCTOU races.
  • On Linux and Android, a netlink dump that the kernel reports as interrupted is attempted up to three times, and persistent interruption returns ErrorKind::Interrupted. A filter sees each entry of a successful dump once and never sees the entries of an attempt that is retried, so a dump interrupted after a large number of entries (on the order of ten thousand) have reached the filter returns ErrorKind::Interrupted instead of being retried.
  • Result ordering is unspecified. There is no general deduplication guarantee; deduplication is promised only where a specific API documents it.
  • IfAddr and IfNet preserve the local interface index. Their derived ordering is enum family followed by stored index and address/network; IpRoute ordering is family followed by index, destination, and gateway. These are value orderings, not routing or address-preference orderings. Interface equality and hashing cover the complete captured snapshot (index, MTU, name, complete hardware-address bytes, and flags), not stable interface identity.
  • Flags::bits() is target-specific raw operating-system data; do not persist or compare those bits across platforms as a portable wire format. Only UP, BROADCAST, LOOPBACK, POINTOPOINT, MULTICAST, and RUNNING are common semantic flags; additional constants are target-dependent.
  • Routes intentionally model only same-family destination/gateway pairs. Cross-family Linux RTA_VIA routes are omitted rather than misrepresented.
  • Interface names are UTF-8 only. A platform can skip an unrepresentable name; getifs does not promise lossless non-UTF-8 name access.
  • ipnet, rfc, probe, SmolStr, SmallVec, and TinyVec are public re-exports and part of the compatibility contract. Serde is not currently exposed; it may be added later as an additive feature.

Android

Android runs the same libc-free netlink backend as Linux, but apps in the untrusted_app SELinux domain hit two extra restrictions, both handled transparently by getifs:

  • bind() on netlink_route_socket is denied (Android bug b/155595000). getifs never binds explicitly; the kernel auto-binds a unique port id on the first send — the same path getifaddrs() and Go's net package rely on.
  • RTM_GETLINK is denied for apps targeting API level 30+ (it needs the nlmsg_readpriv permission). Interface metadata therefore falls back to discovering indices via RTM_GETADDR (which stays permitted) and reading the name / MTU / flags with SIOCGIF* ioctls on a datagram socket.

Working inside the untrusted_app sandbox: interfaces(), interface_by_index(), interface_by_name(), MTU, every address query (interface_addrs(), local_addrs(), private_addrs(), public_addrs()), gateways, and the routing table.

Caveats on Android 11+ (API level 30+):

  • interfaces() lists only interfaces that currently have an address — there is no app-permitted way to enumerate address-less ones without getifaddrs. (interface_by_index() / interface_by_name() are unaffected.)
  • The hardware (MAC) address is reported as None (Android restricts it for apps).
  • Interfaces with a non-UTF-8 name are skipped.
  • The ioctl socket requires the android.permission.INTERNET permission (which any networking app already holds).

On every Android version, multicast group enumeration returns io::ErrorKind::Unsupported. The Linux backend reads group memberships from /proc/net/igmp*, which apps cannot read on Android 10+, so the Android build does not attempt it.

Performance

Existing network interface crates mostly don't support MTU or multicast addresses, nearly all use libc::getifaddrs, which is slower, and they make heavy use of heap allocations for simple queries. getifs is faster because it:

  • Makes direct system calls: uses platform-native APIs (netlink on Linux, sysctl on BSD/macOS, IP Helper on Windows).
  • Parses without copying: zero-copy parsing with minimal allocations and efficient buffer reuse.
  • Has no libc dependency on Linux: direct netlink socket communication.
  • Avoids heap allocations for common cases: it uses SmallVec and SmolStr as its data structures.

It also provides comprehensive interface information, including MTU and multicast support.

getifs achieves significantly better performance than alternatives:

  • Up to 72x faster on macOS (interface_by_index)
  • Up to 22x faster on macOS (list interfaces)
  • 2.4–2.8x faster on Linux (interface enumeration)
  • ~6.8x faster local-IP lookup on Linux
  • 15–86x faster interface listing and lookup on Windows; address queries are on par (GetAdaptersAddresses overhead dominates)

All benchmarks are run with Criterion.rs on GitHub Actions. Lower is better.

Note: Automated benchmarks run on Linux, macOS, and Windows via GitHub Actions. View the latest results in the Actions tab or see benchmark documentation for more details.

Summary

Numbers below compare getifs against network-interface 2 and local-ip-address 0.6. Each row reports median cargo bench time (Criterion, 100 samples), measured on GitHub Actions macos-latest (ARM64) / ubuntu-latest (x64) / windows-latest (x64) runners. The macOS and Linux measurements are from 2026-05-06; the Windows measurements are from 2026-10-07.

Platform Best Operation getifs Alternative Speedup
macOS (ARM64) Get interface by index 2.6 μs 187.4 μs 72x faster
macOS (ARM64) List all interfaces 8.5 μs 187.7 μs 22x faster
Linux (x64) Local IPv4 lookup 13.7 μs 93.3 μs 6.8x faster
Linux (x64) List all interfaces 42.7 μs 113.7 μs 2.7x faster
Windows (x64) Gateway IPv4 35.5 μs N/A Unique feature

Detailed results

Interface operations

macOS (GitHub Actions ARM64)

Operation getifs Alternative Speedup
List all interfaces 8.5 μs 187.7 μs (network-interface) 22x faster
Get interface by index 2.6 μs 187.4 μs (network-interface) 72x faster
Get interface by name 11.4 μs 187.8 μs (network-interface) 17x faster
Get interface addresses 8.5 μs - -
Get multicast addresses 4.6 μs - -

Linux (GitHub Actions x64)

Operation getifs Alternative Speedup
List all interfaces 42.7 μs 113.7 μs (network-interface) 2.7x faster
Get interface by index 40.7 μs 113.4 μs (network-interface) 2.8x faster
Get interface by name 46.4 μs 113.5 μs (network-interface) 2.4x faster
Get interface addresses 17.2 μs - -
Get multicast addresses 31.6 μs - -

Windows (GitHub Actions x64)

Operation getifs Alternative Speedup
List all interfaces 59.6 μs 877.6 μs (network-interface) 15x faster
Get interface by index 10.2 μs 872.1 μs (network-interface) 86x faster
Get interface by name 49.0 μs 875.0 μs (network-interface) 18x faster
Get interface addresses 875.8 μs - -
Get multicast addresses 872.5 μs - -

Note: interface listing and lookup read the IP Helper interface table. Address queries still go through GetAdaptersAddresses, whose ~1 ms floor dominates every implementation that uses it, network-interface included.

Local IP address operations

macOS (GitHub Actions ARM64)

Operation getifs Alternative Speedup
Get local IPv4 address 6.2 μs 9.9 μs (local-ip-address) 1.6x faster
Get local IPv6 address 7.8 μs 9.5 μs (local-ip-address) 1.2x faster

Linux (GitHub Actions x64)

Operation getifs Alternative Speedup
Get local IPv4 address 13.7 μs 93.3 μs (local-ip-address) 6.8x faster
Get local IPv6 address 11.3 μs - No IPv6 result from alternative

Windows (GitHub Actions x64)

Operation getifs Alternative Notes
Get local IPv4 address 1110 μs 1062 μs (local-ip-address) Win32 ~1 ms floor
Get local IPv6 address 1104 μs 1120 μs (local-ip-address) Win32 ~1 ms floor
Gateway operations
Platform IPv4 Gateways IPv6 Gateways All Gateways
macOS (ARM64, CI) 24.3 μs 3.4 μs 26.8 μs
Linux (x64, CI) 19.9 μs 16.1 μs 24.1 μs
Windows (x64, CI) 35.5 μs 21.8 μs 58.4 μs

Note: No direct alternatives available for gateway discovery, so these are reported as absolute times rather than as speedups.

Route table operations
Platform IPv4 routes IPv6 routes All routes Default-only filter
macOS (ARM64, CI) 28.1 μs 12.2 μs 41.0 μs 40.8 μs
Linux (x64, CI) 30.1 μs 26.6 μs 34.8 μs 34.6 μs
Windows (x64, CI) 65.1 μs 22.5 μs 81.7 μs 80.8 μs

Note: The default_only filter result is essentially identical to the unfiltered route_table because the closure runs after each row is built — the dominant cost is the kernel dump itself, not the per-row filter. No direct alternatives expose a routing-table API for comparison.

Platform notes

  • macOS: Shows the largest speedups (17–72x on the ARM64 CI runners) due to the efficient sysctl-based implementation avoiding getifaddrs's per-call overhead.
  • Linux: 2.4–2.8x faster interface enumeration via direct netlink, and ~6.8x faster local-IP lookup from avoiding the test-socket round trip that local-ip-address performs.
  • Windows: Interface listing and lookup read the IP Helper interface table instead of GetAdaptersAddresses, so they are 15–86x faster than network-interface. Address and local-IP queries still use GetAdaptersAddresses, whose ~1 ms floor dominates every implementation, so they are on par. Gateway and route-table queries skip that path entirely (~36 μs gateway / ~80 μs full table); getifs only — the alternatives don't expose them.

Maintenance

The MSRV is Rust 1.85. smol_str 0.3.4 and later require Rust 1.89, so on Rust 1.85–1.88 enable Cargo's MSRV-aware resolver (resolver.incompatible-rust-versions = "fallback" in Cargo configuration, or package.resolver = "3") or run cargo update -p smol_str --precise 0.3.2.

The direct macro dependency is the maintained pastey crate, aliased as paste so existing macro invocations remain compatible. RUSTSEC-2024-0436 identifies the older paste crate as unmaintained, not as a known vulnerability. Transitive uses can still be selected by smallvec-wrapper; this crate does not modify that upstream dependency graph.

Fuzzing

The detached fuzz workspace contains cfg-only parser drivers for Linux/Android netlink and Apple/BSD sockaddr parsing. These hooks are not normal public API. Generate its deterministic corpus before running cargo fuzz; pull requests use fixed runs and scheduled/manual CI bounds each target to 60 seconds.

Related crates

Sister crates:

  • iprobe: Probe if the host system supports IPv4, IPv6 and IPv4-mapped-IPv6.
  • iprfc: Known RFCs for IP addresses.

Pedigree

License

getifs is under the terms of both the MIT license and the Apache License (Version 2.0).

See LICENSE-APACHE, LICENSE-MIT for details.

Copyright (c) 2026 Al Liu.

About

Cross-platform enumeration of network interfaces and their MTU, gateway, multicast, and local/private/public IP addresses — with a libc-free netlink backend on Linux and no getifaddrs dependency.

Topics

Resources

Contributing

Security policy

Stars

27 stars

Watchers

1 watching

Forks

Releases

Sponsor this project

Packages

Contributors

Languages

Generated from al8n/template-rs