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.
[dependencies]
getifs = "0.8"The minimum supported Rust version is 1.85; see Maintenance for the smol_str resolver note.
- 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):
InterfaceSnapshotwith 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_*andprivate_*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.
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);
}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());
}
}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 | 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.
| 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) |
The APIs in this guide are new in 0.8.
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, andpredicate::flagsare typed constructors.- Any Rust closure accepting an
InterfaceAddressis also anInterfacePredicate;.and(),.or(), and.not()short-circuit. AddressComparatorprovides.then()and.reverse(), and theordermodule 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() 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; IPv6local,main) with metric and IPv6 router-preference ordering:- A winning default route of any type other than
unicast,local, orthrow(blackhole,unreachable,prohibit, and others such asnatorbroadcast) means no default interface. throwfalls 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 rulepolicy tables are not modeled.
- A winning default route of any type other than
- 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
/0route, so split-default halves such as0.0.0.0/1and::/1are 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_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.
_byvariants replace only the ranking; they cannot make down or nonforwardable candidates eligible.
The mixed-family default ranking, in order:
- Family-default membership.
- IPv4 before IPv6.
- Larger network (smaller prefix).
- Lower interface index.
- Numeric address.
- 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.
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.
CheckedIpAddrExt offers checked addition and subtraction for Ipv4Addr,
Ipv6Addr, and IpAddr. UsableIpNetExt provides usable-host indexing:
- IPv4
/0through/30exclude network and broadcast. /31includes both endpoints./32has 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>>(())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 compatibleiprfc1.x release, not an immutable snapshot tied to a getifs release.get_interface_mtuandget_ifaddr_mtureturn a local link MTU, not a remote path MTU. IP-only MTU lookup returnsNotFoundfor no local match andInvalidInputfor an address assigned to distinct interfaces. IPv6 link-local addresses should be queried with theirIfAddrscope.interface_by_indexandinterface_by_namereturnOk(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 olderifname_to_v6_ifaceandifname_to_ifaceretain their historicalOptionmeanings; 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 returnsErrorKind::Interruptedinstead of being retried. - Result ordering is unspecified. There is no general deduplication guarantee; deduplication is promised only where a specific API documents it.
IfAddrandIfNetpreserve the local interface index. Their derived ordering is enum family followed by storedindexand address/network;IpRouteordering is family followed byindex, destination, and gateway. These are value orderings, not routing or address-preference orderings.Interfaceequality 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. OnlyUP,BROADCAST,LOOPBACK,POINTOPOINT,MULTICAST, andRUNNINGare common semantic flags; additional constants are target-dependent.- Routes intentionally model only same-family destination/gateway pairs.
Cross-family Linux
RTA_VIAroutes 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, andTinyVecare public re-exports and part of the compatibility contract. Serde is not currently exposed; it may be added later as an additive feature.
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()onnetlink_route_socketis denied (Android bug b/155595000).getifsnever binds explicitly; the kernel auto-binds a unique port id on the first send — the same pathgetifaddrs()and Go'snetpackage rely on.RTM_GETLINKis denied for apps targeting API level 30+ (it needs thenlmsg_readprivpermission). Interface metadata therefore falls back to discovering indices viaRTM_GETADDR(which stays permitted) and reading the name / MTU / flags withSIOCGIF*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 withoutgetifaddrs. (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.INTERNETpermission (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.
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
SmallVecandSmolStras 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 (
GetAdaptersAddressesoverhead 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.
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 |
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.
- 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-addressperforms. - Windows: Interface listing and lookup read the IP Helper interface
table instead of
GetAdaptersAddresses, so they are 15–86x faster thannetwork-interface. Address and local-IP queries still useGetAdaptersAddresses, 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);getifsonly — the alternatives don't expose them.
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.
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.
Sister crates:
iprobe: Probe if the host system supports IPv4, IPv6 and IPv4-mapped-IPv6.iprfc: Known RFCs for IP addresses.
- The code in this crate is inspired by Golang's
interface.goand HashiCorp's go-sockaddr.
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.