go-linux

Routing Netlink

netlink/route provides typed operations for interfaces, IPv4 and IPv6 addresses, neighbors, routes, nexthop objects, and policy rules over netlink. It owns request and notification sockets internally. Use standard net for ordinary network I/O; use this package for Linux interface configuration, routing identifiers, and multicast changes. See the package reference and rtnetlink(7).

Good for

Good for network inventory, interface configuration, and routing agents that react to kernel changes. iproute2’s ip route implementation uses the same routing Netlink mechanism for route queries and mutations.

Read current state

conn, err := route.Open(netlink.Options{Validation: netlink.StrictValidation})
if err != nil {
    return err
}
defer conn.Close()

if err := conn.SetDeadline(time.Now().Add(5 * time.Second)); err != nil {
    return err
}
links, err := conn.Links()
if err != nil {
    return err
}
for _, link := range links {
    fmt.Println(link.Index, link.Name, link.MTU, link.Flags&route.Up != 0)
}

Import github.com/alexfalkowski/go-linux/v2/netlink/route and github.com/alexfalkowski/go-linux/v2/netlink, plus the standard packages used above. Addresses, Routes, Neighbors, and Rules each select one IP family. Use route.IPv4 or route.IPv6. Links lists interfaces independently of IP configuration. The executable examples cover interface and route listing.

Each list is a separate kernel dump, not an atomic snapshot or transaction. A failed, interrupted, oversized, or malformed dump returns a nil list. An empty successful dump returns an empty slice. Results remain valid after subsequent calls and Close. Interface indices and other identifiers can be reused after removal.

Link.Flags preserves Linux IFF_* values, which differ from net.Flags. Link.MasterIndex identifies the master interface in the same namespace, with zero indicating no reported master. Address.Prefix retains the local host bits: 192.0.2.1/24 is an address, not the masked route prefix 192.0.2.0/24. Linux IFA_LOCAL wins over IFA_ADDRESS; a differing IFA_ADDRESS appears as Peer. The full IFA_FLAGS attribute overrides the header’s eight-bit fallback. Route.Source is a source selector, distinct from PreferredSource. Table retains full 32-bit IDs, including an RTA_TABLE override of the fixed header.

Records retain all original Attributes, including unknown IDs, output flags, nested route data, cache lifetimes, and link-kind metadata. The typed fields interpret a bounded subset. Route.Index and Route.Gateway report the top-level path. Call Route.NextHops for inline paths, cross-family gateways, or nexthop object references. ParseLink, ParseAddress, ParseRoute, ParseNexthop, ParseNeighbor, ParseRule, and ParseEvent also decode messages obtained through the base Netlink package. These parsers borrow attribute bytes from the input; they reject malformed interpreted fields and duplicate interpreted attributes while preserving unknown attributes and repetitions. They do not validate the schemas of opaque attributes.

Change configuration

Mutations need applicable CAP_NET_ADMIN and kernel support in the connection’s network namespace. Open captures the calling thread’s current namespace through socket creation; this package does not change namespaces. Check each returned error. Changes persist after closing the connection, and address/link deletion can remove associated routes.

AddLink creates a route.Dummy or route.Bridge with exclusive-create semantics and kernel defaults. The corresponding driver must be available and requesting it can trigger module autoloading. List links to obtain the assigned index. ChangeLink(index, route.LinkChange{Flags: route.Up, Change: route.Up}) brings an interface up. Change: route.Up with zero Flags brings it down. Name and nonzero MTU optionally rename the link or set its MTU. Only the documented mutable flag mask is accepted, and Flags must be a subset of Change. Zero Name and MTU leave those properties untouched. A multi-property change can partially apply before a kernel error. DeleteLink(index) asks Linux to remove that interface, subject to device restrictions.

Connect a workload to a bridge

Create both veth endpoints in the source network namespace, then use the indices from Links to attach the host endpoint and move the peer. Run these mutations in a network namespace you administer. The target is a live network *namespace.Handle, such as one opened from a child process’s /proc/<pid>/ns/net. Namespace usage guide.

if err := conn.AddLink("bridge0", route.Bridge); err != nil {
    return err
}
if err := conn.AddVeth(route.VethConfig{Name: "host0", PeerName: "peer0"}); err != nil {
    return err
}
// Resolve bridgeIndex, hostIndex, and peerIndex by name with conn.Links().
if err := conn.SetLinkMaster(hostIndex, bridgeIndex); err != nil {
    return err
}
if err := conn.MoveLink(peerIndex, target, route.LinkMove{Name: "eth0"}); err != nil {
    return err
}

AddVeth creates the pair in one exclusive request. Use distinct literal names from 1 to 15 bytes. Deleting either endpoint removes both, even across namespaces. Deleting a bridge detaches its ports. ClearLinkMaster detaches one port while keeping its link. Replacing a master can detach the old one before Linux rejects the new one. Use Links and MasterIndex to reconcile the state after an error. Veth creation and deletion example.

MoveLink borrows the target handle and requires administration privileges for both namespaces. With LinkMove{}, the old name must be free in the destination. Supply a literal Name to request a rename, including when the target is the source namespace. Linux can move a link first and then reject the rename, leaving the link in the target under its old name. A move brings the link down and can remove namespace-local configuration, including addresses, routes, or master membership. The index may change. Observe both namespaces after an ambiguous result and resolve the link in the target before configuring it. Open a target connection on a dedicated locked goroutine or inside the workload process. MoveLink itself leaves the calling thread’s namespace unchanged. Namespace entry and connection example.

Bring the bridge, port, and peer links up as needed. Use AddAddress and AddRoute for the workload’s IP configuration and standard net for traffic. This API uses the bridge driver’s defaults for STP and VLAN configuration. Closing a connection or a namespace handle releases that reference. When the kernel destroys a namespace containing either veth endpoint, it removes the pair.

Configure addresses and routes

For an existing positive interface index, the address request is explicit:

config := route.AddressConfig{
    Index: index,
    Prefix: netip.MustParsePrefix("192.0.2.1/24"),
    Flags: route.NoPrefixRoute,
}
if err := conn.AddAddress(config); err != nil {
    return err
}
// Later, when removal is intended:
if err := conn.DeleteAddress(config); err != nil {
    return err
}

AddressConfig supports an optional same-family peer, IPv4 broadcast/label, scope, NoDAD/NoPrefixRoute, and automatic prefix-route priority. An invalid peer means use the local address; invalid optional broadcast means omit it. Zone suffixes are not inputs: Index supplies the interface identity. Host bits in Prefix are preserved. Add/change omit cache lifetimes and request permanent lifetime; finite lifetimes and address generation policies are outside this API.

AddAddress uses CREATE|EXCL; ChangeAddress uses REPLACE. Linux can create an absent address on replacement, even without CREATE. IPv4 replacement updates lifetime and prefix-route priority while retaining existing flags, scope, label, peer, and broadcast. IPv6 modification follows its kernel rules, including flag changes. Replacement is not a general rewrite of every config field. Delete uses the local/peer/prefix identity. Zero priority requests the kernel default on creation; on replacement, it resets IPv4 priority to its default but preserves an existing IPv6 priority.

AddRoute, ChangeRoute, and DeleteRoute accept RouteConfig. Destination must be a valid, masked IP prefix; default routes are explicitly 0.0.0.0/0 or ::/0. Optional Gateway and PreferredSource must be unzoned and in the destination family. Index selects an output interface; zero leaves selection to Linux. Table zero selects MainTable, including for deletion. Protocol/Type zero use BootProtocol/Unicast for add/change and remain unspecified selectors on delete. Priority zero omits the metric, which can act as a wildcard on delete. Scope zero is Universe; callers normally choose LinkScope for an IPv4 direct route. Unicast, Local, Blackhole, Unreachable, and Prohibit are the accepted mutation types; device and family restrictions remain kernel errors.

Route add uses CREATE|EXCL; change uses REPLACE without CREATE. Linux chooses replacement identity, including the route metric. This does not implement a userspace delete/recreate sequence or an existence preflight. Deletion can match unspecified fields as wildcards; provide enough identity to select the intended route. Construct mutations from explicit configuration. Observed metrics, encapsulation, and other metadata remain available in Attributes.

Resolve a workload’s route

query := route.RouteQuery{
    Destination: netip.MustParseAddr("198.51.100.7"),
    Mark:        0x1234,
}
path, err := conn.LookupRoute(query)
if err != nil {
    return err
}
fmt.Println(path.Table, path.Index, path.Gateway)

LookupRoute returns one resolved path. MatchRoute runs the same flow lookup and asks Linux for the matching installed entry, including its prefix, table, and any extended paths. A resolved result can point to a single interface when the installed entry has several paths. Both calls use the connection’s network namespace and its policy rules. Route lookups can return kernel errors for unreachable or rejected flows.

An optional source must be unzoned and in the destination’s address family. Use InputIndex for an incoming lookup or OutputIndex to constrain local output. Leave both at zero for ordinary local selection. Queries also accept a mark, TOS or IPv6 traffic class, optional UID, IP protocol, and TCP or UDP ports in host byte order. The kernel chooses the defaults for omitted fields. A lookup reports the kernel’s decision at the time of the request.

Configure weighted paths and nexthop objects

config := route.RouteConfig{Destination: netip.MustParsePrefix("198.51.100.0/24"), Priority: 100}
paths := route.RoutePathConfig{Multipath: []route.RouteNextHopConfig{
    {Index: primaryIndex, Gateway: netip.MustParseAddr("192.0.2.1"), Weight: 3},
    {Index: secondaryIndex, Gateway: netip.MustParseAddr("192.0.2.2"), Weight: 1},
}}
if err := conn.AddRouteWithPaths(config, paths); err != nil {
    return err
}

Set exactly one of RoutePathConfig.Multipath and NexthopID. Leave the top-level RouteConfig.Index and Gateway unset. Inline weights range from 1 through 256. IPv4 inline entries can use a device alone or an unzoned IPv4 or IPv6 gateway. IPv6 inline entries require an IPv6 gateway. OnLink explicitly treats a supplied gateway as directly attached. Route.NextHops preserves the flags, gateway families, weights, and nested metadata reported in inline multipath entries. Linux reports a single inline path as top-level attributes without its weight. NextHops validates extended path attributes on demand. Routes and route notifications retain the outer record and its raw attributes.

ChangeRouteWithPaths issues a replacement under the same family-specific identity rules as ChangeRoute. For deletion, supply the prefix, table, and metric that identify the intended route. DeleteRouteWithPaths adds kernel path selectors. IPv4 compares installed paths in order and ignores weights, flags, and extra requested paths. An omitted IPv4 path gateway is a wildcard. IPv6 attempts each requested inline path separately, so an error can follow a successful removal of another path. Linux can also remove a matching IPv6 route that references a nexthop object even when its interface and gateway differ from the requested inline path. Use NexthopID to require an object ID match. A failed IPv6 inline replacement can also leave changes. Re-read the affected table after an ambiguous result.

Use AddNexthop to create a forwarding object, a blackhole object, or a weighted hash-threshold group. Choose a nonzero namespace-local ID. Use an active interface for a forwarding object. IPv4 blackhole objects use the namespace’s loopback interface, which must be up. A group uses existing single-object IDs, each appearing once with a weight from 1 through 65535. Use RoutePathConfig{NexthopID: id} to share an object across routes. Nexthop(id) reads one object, and Nexthops() lists ordinary routing objects across families. When a route contains both an object ID and compatibility inline paths, query the object for authoritative group weights. The inline weight field has a smaller range.

ChangeNexthop replaces an existing object by ID. Routes can continue to reference that ID and use the new configuration. DeleteRouteWithPaths removes the selected route and leaves its referenced object available. DeleteNexthop can remove referencing routes and change or remove dependent groups. Objects and routes persist after the request connection closes. Resilient group settings and encapsulation remain available as observation attributes. Executable route examples.

Manage ARP and NDP entries

Use Neighbors(route.IPv4) for the ARP cache and Neighbors(route.IPv6) for the NDP cache. Records preserve Linux state and flag bits and the reported hardware address. The hardware address can be absent while resolution is incomplete or has failed. Cache information and probe counts remain available in Attributes.

Use AddNeighbor to claim a new address/interface pair and ChangeNeighbor to update an existing pair. Both take a NeighborConfig with a positive interface index, an unzoned IP address, and one reachability state. Use NeighborPermanent for a static mapping. Linux validates the hardware address for the interface. An add can leave an entry in the cache when initial configuration fails. When changing an entry, omitting its hardware address lets Linux retain it where the requested state permits. Zero protocol leaves the installer unchanged on update.

Use ChangeNeighbor for entries whose administrative flags you manage. Replacement can clear omitted router and externally learned flags. It can also clear managed and externally validated flags, which are observation-only in this API. A kernel rejection can still change flags or the installer protocol. Use a fresh dump to reconcile the observed state.

An existing pair causes EEXIST on add and a missing pair causes ENOENT on change. DeleteNeighbor(index, address) matches the exact pair in the address’s family. Entries still in use can remain in the failed state after deletion. All three operations act on ordinary neighbors. ParseNeighbor can also decode proxy ARP/NDP records obtained through base Netlink proxy queries or dumps. A proxy that applies to all interfaces has index zero. Neighbor example.

Select a routing table with a policy rule

Populate the target table with AddRoute, then add a rule that selects it. For example, a workload manager can route traffic sourced from one workload prefix through table 1001:

config := route.RuleConfig{
    Family: route.IPv4, Priority: 100, Action: route.RuleLookup, Table: 1001,
    Selector: route.RuleSelector{Source: netip.MustParsePrefix("192.0.2.0/24")},
}
if err := conn.AddRule(config); err != nil {
    return err
}

Rules(family) lists rules, including the kernel’s default rules. Lower priorities are evaluated first. RuleConfig sends its priority even when it is zero. Choose a distinct priority for each managed rule. AddRule requests exclusive creation according to Linux’s duplicate predicate. Different rules can share a priority. DeleteRule removes the first kernel match and reports ENOENT when none matches. It always supplies a priority and action. Omitted selectors can match any value, and Linux’s deletion predicate ignores inversion and goto target. For a masked mark, Linux compares a supplied nonzero mark and mask independently when deleting. A nonzero mark with an omitted mask uses all bits for both add and delete. A zero mark can match another rule with the same mask and otherwise matching fields. Linux exposes add and delete as separate rule operations.

A rule supports masked source and destination prefixes, input and output interface names, the legacy TOS field, netfilter mark and mask, socket-owner UID range, IP protocol, and source or destination port selectors. Rule actions include table lookup, forward goto, no-op, and blackhole, unreachable, and prohibited results. A goto without a present target is reported with RuleUnresolved. An interface name can remain in a rule while its device is absent. Use RuleInvert to invert the selectors. The rule installer protocol is separate from the packet’s IP protocol. Kernel attributes outside this configuration surface, including L3 master, tunnel ID, dedicated DSCP/flow-label, and suppression selectors, remain available in Rule.Attributes. Policy-rule example.

Leave a prefix selector at its zero value to omit it. Supplied prefixes must be valid, masked, and belong to the rule’s IP family. A netip.PrefixFrom result with an out-of-range length is rejected with os.ErrInvalid when it retains an address.

To add or delete a rule with a UID range, the calling thread must be in the user namespace that owns the connection’s network namespace. Both endpoints must map to UIDs in that user namespace.

Observe changes

Listen opens a separate socket in the calling thread’s current network namespace. Choose one or more supported groups. NeighborGroup covers both IP families, while IPv4RuleGroup and IPv6RuleGroup subscribe separately. NexthopGroup subscribes to nexthop object changes across families. Combine groups to observe the relevant link, address, neighbor, rule, route, and object changes. Use SetReadDeadline to bound ReadEvents, which consumes one datagram per call. Each event has one populated record pointer among Link, Address, Route, Neighbor, Rule, and Nexthop. Convert positional Event literals to keyed fields to include the added record slot.

NewLink, NewAddress, NewRoute, NewNeighbor, and NewNexthop report creation or later changes. NewRule reports insertion. The corresponding Del* types report removal. A mutation can emit several events. The kernel sends bridge forwarding database events on the neighbor group and resilient nexthop bucket events on NexthopGroup. ReadEvents skips these events and can return an empty batch when a datagram contains only skipped events.

Notifications can be lost. ENOBUFS, netlink.ErrTruncated, and unsupported or malformed records return an error with no partial batch. The listener stays open, including after deadline expiration; rebuild state over a separate request connection when continuity is lost. Returned records remain valid after later reads and Close. There is no atomic subscribe-and-dump handshake or automatic reconciliation. Consumers own scheduling and any channels; concurrent readers compete for datagrams.

Ownership, errors, and limits

Open/Listen return nil and release all acquired sockets/memberships on failure. Owners must be used through pointers and not copied. Zero owners return os.ErrInvalid; repeated Close and valid operations after Close match os.ErrClosed. Validation happens before I/O, so invalid arguments still match os.ErrInvalid on a closed connection. Constructors accept the base package’s explicit receive/accumulation limits; zero options use its defaults. Deadlines default to unbounded, so set them for bounded waits.

Requests serialize per connection. Close and deadline setters can interrupt active I/O; deadlines do not bound waiting for the request lock. An incomplete exchange closes the underlying request connection, preventing unread replies from affecting later requests. A fully drained dump with a typed-decoding error leaves it open. Completed kernel rejections preserve errno and extended error diagnostics through *netlink.Error, and leave it usable. Receive timeout matches os.ErrDeadlineExceeded. No transport error proves a mutation was not applied, and the package never retries or rolls back mutations.

Traffic control, proxy ARP/NDP configuration, bridge forwarding database management, other virtual link types, bridge tuning, nexthop bucket management and resilient group mutation, route encapsulation and metrics mutations, finite address lifetimes, and transactions are outside this operation set. The design note explains the boundaries. Verification owns runner commands and isolation, and verification limits records missing execution evidence.

NAT and firewall policy belong to a separate Netfilter integration. Linux 7.0 routing UAPI, container lifecycle composition.