Website Vidya
Linux & ServersStep-by-Step Guide

Linux ip Command: Networking Syntax, Flags & Practical Examples

Learn linux ip command with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

RR
Rajesh RayLead Systems Educator
Published:
13 min read
PDF Cheat Sheet
Linux ip Command: Networking Syntax, Flags & Practical Examples
AI Executive SummaryWebsiteVidya AI

13 min read

Learn linux ip command with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

Key Highlights
  • What ip Does and When to Use It
  • Availability and Installation Across Linux Distributions
  • Command Syntax, Arguments, and Exit Status Codes
Grounded in full engineering runbookWebsiteVidya AI Engine

Modern Linux server administration relies on the linux ip command as the authoritative interface for configuring kernel networking subsystems. Provided by the iproute2 package, ip superseded the legacy net-tools suite (ifconfig, route, arp, and netstat) because net-tools relied on deprecated ioctl system calls that could not express modern Linux kernel features such as policy-based routing, multiple routing tables, VXLAN overlays, or network namespaces.

Whether you are debugging connectivity on a bare-metal hypervisor, configuring secondary elastic IP addresses on cloud instances, or inspecting virtual Ethernet (veth) pairs inside a Kubernetes worker node, ip provides direct, atomic access to the kernel networking stack. Changes applied with ip take effect immediately in kernel memory without requiring a network daemon restart, though persistent configuration across reboots should also be declared in NetworkManager, systemd-networkd, or Netplan.

This technical reference covers how ip communicates with the kernel over Netlink sockets, explains its object-oriented command grammar, details essential diagnostic flags like -brief and -json, and walks through real-world production examples and automation pipelines.

Advertisement
Linux ip Command: Networking Syntax, Flags & Practical Examples — syntax, flags, and practical terminal workflow diagram
Linux ip Command: Networking Syntax, Flags & Practical Examples — command syntax, key options, and production workflow reference.

What ip Does and When to Use It

Unlike legacy networking tools that iterated over /proc/net text files or issued individual ioctl() calls per interface attribute, the ip utility communicates with the Linux kernel using Netlink sockets (specifically the AF_NETLINK family with the NETLINK_ROUTE protocol). Netlink operates as an asynchronous, message-based IPC mechanism between userspace and kernel space, allowing ip to request bulk dumps of link states, IPv4/IPv6 prefixes, neighbor tables, and routing rules in structured binary Type-Length-Value (TLV) attributes.

Because Netlink operations are transactional at the message level, adding CIDR addresses, toggling link administrative states, or inserting Equal-Cost Multi-Path (ECMP) routes happens atomically. Furthermore, ip natively understands modern kernel abstractions including Virtual Routing and Forwarding (VRF) domains, WireGuard and GRE tunnels, bridgefdb tables, and isolated network namespaces (/var/run/netns) used by container runtimes such as containerd and CRI-O.

At the operating system level, ip interacts with the Linux kernel networking stack through netlink sockets (AF_NETLINK), raw packet sockets, or standard POSIX resolver APIs. When running ip in cloud instances or Kubernetes worker nodes, combining flags such as -4, -6, -br, -c lets you bypass slow reverse DNS lookups and inspect numeric IPv4/IPv6 addresses and socket states directly.

Availability and Installation Across Linux Distributions

The ip utility is packaged in iproute2 across mainstream Linux distributions. It is pre-installed on standard Ubuntu, Debian, RHEL, Rocky Linux, AlmaLinux, Fedora, and Arch Linux systems, while minimal container images may require manual installation:

Advertisement

Before running administrative tasks or automation scripts, verify whether ip is installed and inspect which binary path and version your shell resolves:

type -a ip
ip --version 2>/dev/null || man -f ip

# Illustrative output (reviewed against documentation)
ip is /usr/bin/ip
ip (iproute2)
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y iproute2

# RHEL / Rocky / AlmaLinux / Fedora
sudo dnf install -y iproute

# Arch Linux
sudo pacman -S --noconfirm iproute2

# Alpine Linux
sudo apk add --no-cache iproute2

Command Syntax, Arguments, and Exit Status Codes

ip [ OPTIONS ] OBJECT { COMMAND | help }

The ip grammar follows a strict hierarchical structure: ip [OPTIONS] OBJECT [COMMAND [ARGUMENTS]]. Global OPTIONS (such as -4, -6, -br, -c, -s, or -j) precede the OBJECT name and alter how data is filtered or formatted. The OBJECT specifies the kernel subsystem you want to inspect or modify: link (network device layer 2 attributes), address (IPv4/IPv6 protocol addresses), route (routing table entries), rule (routing policy database), neigh (ARP and NDISC neighbor caches), or netns (network namespaces).

Crucially, the parser supports unambiguous prefix abbreviation for both objects and commands. For example, ip address show, ip addr sh, and ip a all invoke the exact same Netlink request. While short abbreviations like ip a and ip r are convenient during interactive troubleshooting sessions, always spell out full object and action names (such as ip address show or ip route replace) in production shell scripts and Ansible playbooks to maximize readability and maintainability.

  • 0 — Command succeeded and all requested Netlink queries or state transitions completed without error.
  • 1 — Syntax error, unrecognized object/subcommand, or invalid command-line option.
  • 2 — Kernel returned an operational error over Netlink (for example, RTNETLINK answers: File exists, Operation not permitted, or nonexistent interface).
  • 255 — Batch mode (ip -batch) encountered one or more failed lines while processing an input file.

Important Options and Flags Reference

Option / FlagLong Form / ArgumentTechnical Behavior and Purpose
-4-family inetRestricts output and modifications strictly to IPv4 protocol addresses, routes, and rules.
-6-family inet6Restricts output and modifications strictly to IPv6 protocol addresses, neighbor entries, and routes.
-br-briefPrints a compact, tabular three-column summary (interface, state, and addresses) ideal for quick visual checks and awk parsing.
-c-color[=always|auto|never]Enables ANSI color highlighting for interface states (UP in green, DOWN in red) and address families.
-j-jsonFormats Netlink responses as valid JSON arrays so automation pipelines can parse output reliably with jq.
-s-stats / -statisticsDisplays detailed per-interface transmit (TX) and receive (RX) packet counters, byte totals, drops, and carrier errors; repeat (-s -s) for extended error counters.
-d-detailsExposes internal device driver metadata, VLAN tags, VXLAN VNI identifiers, bridge port parameters, and tunnel endpoints.
-n-netns <NAME>Switches the ip process into the specified network namespace under /run/netns/ before opening the Netlink socket.
-b-batch <FILE>Reads and executes a sequence of ip subcommands from a file or standard input to speed up bulk route or rule provisioning.

Combining formatting flags dramatically improves CLI ergonomics and script reliability. During interactive SSH sessions, running ip -br -c addr show gives you an instant color-coded overview of every interface, its operational carrier state, and its assigned CIDR blocks without scrolling through dozens of lines of broadcast, qdisc, and lifetime lines.

Advertisement

When writing monitoring checks or infrastructure discovery scripts, avoid scraping default multi-line human output with fragile regular expressions. Instead, pass -j (-json) alongside -d (-details) and -s (-stats) so that ip emits deterministic JSON objects containing exact numeric fields like ifindex, operstate, mtu, and stats64.

When combining short flags on the command line, POSIX and GNU utilities allow clustering boolean flags behind a single hyphen, provided any option taking an argument appears last. In automated shell scripts, using long-form GNU options where portable makes self-documenting code that is easier to audit during peer review.

Practical Basic and Advanced Usage Examples

1. Inspect All Network Interfaces in Compact Brief Format

Use the -br (brief) and -c (color) flags with the addr object to view a clean tabular overview of all physical, loopback, and virtual interfaces along with their operational state and assigned IPv4/IPv6 CIDR addresses.

ip -br -c addr show

# Illustrative output (reviewed against documentation)
lo               UNKNOWN        127.0.0.1/8 ::1/128
eth0             UP             10.24.16.42/24 metric 100 fe80::5054:ff:fe12:3456/64
docker0          DOWN           172.17.0.1/16

The first column shows the kernel interface name, the second displays the administrative/carrier status (UP, DOWN, or UNKNOWN for loopback), and the third lists all configured IP prefixes.

2. Assign and Remove a Secondary IPv4 Address Live

Add a secondary CIDR address to an active network interface using ip addr add without disrupting existing TCP sessions on the primary address, and verify or remove it cleanly.

sudo ip addr add 10.24.16.100/24 dev eth0 label eth0:vip
ip -4 -br addr show dev eth0

# Illustrative output (reviewed against documentation)
eth0             UP             10.24.16.42/24 10.24.16.100/24

Always specify the correct subnet prefix length (such as /24); omitting the mask defaults to /32, which prevents local subnet communication unless explicit host routes exist. To delete the address later, run sudo ip addr del 10.24.16.100/24 dev eth0.

3. Bring an Interface Up or Change Its MTU at Layer 2

Use the ip link object to change the administrative state of a network card or adjust its Maximum Transmission Unit (MTU) for jumbo frames on storage networks.

sudo ip link set dev eth1 mtu 9000 up
ip -d link show dev eth1

# Illustrative output (reviewed against documentation)
3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 9000 qdisc mq state UP mode DEFAULT group default qlen 1000
    link/ether 52:54:00:8a:9b:1c brd ff:ff:ff:ff:ff:ff promiscuity 0 minmtu 68 maxmtu 9216

Within the angle brackets, UP indicates the kernel administrative flag (IFF_UP) is enabled, while LOWER_UP confirms that physical Layer 1 carrier sense (cable link or virtual switch attachment) is established.

4. Inspect the Kernel Routing Table and Query Exact Path Selection

Display all IPv4 routes in the main routing table and use ip route get to ask the kernel exactly which interface, source IP, and next-hop gateway it will select to reach a specific destination.

ip -4 route show
ip route get 8.8.8.8

# Illustrative output (reviewed against documentation)
default via 10.24.16.1 dev eth0 proto dhcp src 10.24.16.42 metric 100
10.24.16.0/24 dev eth0 proto kernel scope link src 10.24.16.42 metric 100
8.8.8.8 via 10.24.16.1 dev eth0 src 10.24.16.42 uid 1000
    cache

While ip route show dumps configured static and dynamic prefixes, ip route get performs a live FIB (Forwarding Information Base) lookup—accounting for policy routing rules, VRFs, and source address selection—making it indispensable when debugging asymmetric routing.

5. Add or Atomically Replace a Static Route

Route traffic destined for an internal private VPC subnet (192.168.50.0/24) through a dedicated transit gateway (10.24.16.254) using ip route replace.

sudo ip route replace 192.168.50.0/24 via 10.24.16.254 dev eth0 metric 50
ip route show 192.168.50.0/24

# Illustrative output (reviewed against documentation)
192.168.50.0/24 via 10.24.16.254 dev eth0 metric 50

Using replace instead of add makes your script idempotent: if the prefix does not exist, the kernel inserts it; if it already exists, the kernel updates the next-hop and metric atomically instead of failing with RTNETLINK answers: File exists.

6. Check Hardware Packet Drops and ARP/Neighbor Cache State

Combine ip -s link and ip neigh show to diagnose packet loss caused by NIC ring buffer drops or stale Layer 2 MAC address resolution on the local LAN.

ip -s link show dev eth0
ip neigh show dev eth0

# Illustrative output (reviewed against documentation)
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP mode DEFAULT group default qlen 1000
    link/ether 52:54:00:12:34:56 brd ff:ff:ff:ff:ff:ff
    RX:  bytes  packets errors dropped  missed   mcast
    8492014420  6120488      0       0       0    1420
    TX:  bytes  packets errors dropped carrier collsns
    3104921104  2940112      0       0       0       0
10.24.16.1 lladdr 00:1b:21:aa:bb:cc REACHABLE
10.24.16.88 INCOMPLETE

In the ip neigh output, REACHABLE means the ARP entry was recently verified, STALE means it is cached but awaiting re-verification on next transmit, and INCOMPLETE or FAILED means ARP requests for that IP received no reply.

Real-World Workflows, Pipelines, and Shell Automation

JSON Interface Telemetry Extraction for Automated Health Checks

In production monitoring scripts, use ip -j -s addr show piped to jq to extract interface names, operational states, IPv4 addresses, and RX/TX drop counters without brittle awk or sed text parsing.

ip -j -s -4 addr show | jq -r '.[] | select(.ifname != "lo") | "\(.ifname)\tstate=\(.operstate)\tip=\(.addr_info[0].local // "none")/\(.addr_info[0].prefixlen // 0)\trx_drop=\(.stats64.rx.dropped)\ttx_drop=\(.stats64.tx.dropped)"'

# Illustrative output (reviewed against documentation)
eth0	state=UP	ip=10.24.16.42/24	rx_drop=0	tx_drop=0

Because iproute2 constructs JSON directly from kernel Netlink attributes, field names remain stable across kernel upgrades and locale settings, ensuring monitoring cron jobs never break on formatting changes.

Isolated Network Namespace Testing with Virtual Ethernet (veth) Pairs

Create an isolated network namespace, connect it to the host namespace via a virtual Ethernet cable (veth pair), assign point-to-point IPv4 addresses, and verify connectivity—mirroring how Docker and Kubernetes CNI plugins wire container pods.

sudo ip netns add blue-ns
sudo ip link add veth-host type veth peer name veth-blue
sudo ip link set veth-blue netns blue-ns
sudo ip addr add 10.200.1.1/24 dev veth-host
sudo ip link set veth-host up
sudo ip -n blue-ns addr add 10.200.1.2/24 dev veth-blue
sudo ip -n blue-ns link set lo up
sudo ip -n blue-ns link set veth-blue up
sudo ip netns exec blue-ns ping -c 2 10.200.1.1

# Illustrative output (reviewed against documentation)
PING 10.200.1.1 (10.200.1.1) 56(84) bytes of data.
64 bytes from 10.200.1.1: icmp_seq=1 ttl=64 time=0.048 ms
64 bytes from 10.200.1.1: icmp_seq=2 ttl=64 time=0.041 ms

Using ip -n blue-ns avoids spawning a full subshell for configuration commands, while ip netns exec blue-ns runs arbitrary user binaries (like ping, curl, or tcpdump) inside the isolated network stack. Clean up afterward with sudo ip netns del blue-ns.

Pipelines, Redirection, Quoting, and Shell Expansion

When embedding ip inside shell pipelines (|), conditional chains (&& and ||), or command substitutions ($(...)), the calling shell performs tilde expansion, variable interpolation, and globbing before invoking the binary. Always wrap paths, patterns, and variables in quotes so whitespace and wildcard characters (*, ?) are not expanded prematurely, and use set -euo pipefail in unattended scripts.

Permissions, Security Implications, and Safe Execution

Read-only Netlink queries—such as viewing interface addresses (ip addr show), routing tables (ip route show), and neighbor entries (ip neigh show)—can be executed by any unprivileged standard user. However, any operation that mutates kernel network state, creates virtual interfaces, flushes caches, or manipulates network namespaces requires the CAP_NET_ADMIN capability (typically granted via root or sudo).

In containerized environments (Docker, Podman, Kubernetes), CAP_NET_ADMIN is dropped by default so an attacker who compromises an application container cannot spoof ARP entries, enable promiscuous packet capture (ip link set promisc on), or hijack pod routing tables. When delegating network management to automation service accounts, grant targeted sudoers rules or ambient capabilities rather than full unrestricted root access.

GNU/Linux, BSD, and BusyBox Implementation Differences

The ip command is specific to the Linux kernel and the iproute2 project because it relies directly on Linux Netlink sockets (AF_NETLINK). On macOS, FreeBSD, OpenBSD, and NetBSD, iproute2 does not exist naturally; those operating systems continue to maintain and modernize their native ifconfig, route, and netstat utilities backed by BSD routing sockets (PF_ROUTE).

On minimal Alpine Linux containers, BusyBox ships a lightweight built-in applet (/sbin/ip) that supports common operations like ip addr, ip route, and ip link, but omits advanced flags such as -json (-j), -color (-c), VRF policy helpers, and extended TCP metrics. If your container scripts require JSON output or advanced policy routing on Alpine, explicitly install the full GNU/Linux iproute2 package with apk add --no-cache iproute2.

Troubleshooting Common Errors and Diagnostics

RTNETLINK answers: File exists

Root Cause: You attempted to run ip addr add or ip route add for an IP prefix or route destination that is already present in the kernel table.

Resolution: Use ip route replace or ip addr change/replace instead of add so the command updates the existing kernel entry idempotently, or inspect current entries first with ip addr show and ip route show.

sudo ip route replace default via 10.24.16.1 dev eth0

RTNETLINK answers: Operation not permitted

Root Cause: The current user lacks the CAP_NET_ADMIN Linux capability in the active user/network namespace when attempting to modify links, addresses, or routes.

Resolution: Prefix the command with sudo on host systems, or if running inside a Docker/Kubernetes container that genuinely needs network configuration rights, add --cap-add=NET_ADMIN to the container security context.

sudo ip link set dev eth0 up

Error: Nexthop has invalid gateway or Network is unreachable

Root Cause: You tried to add a route via a gateway IP address for which the kernel has no directly connected local subnet (scope link) route on any active UP interface.

Resolution: Ensure the interface connected to the gateway's subnet is UP and has a local IP address in that CIDR range, or pass the onlink flag if the gateway is reachable over the link despite being outside the local subnet mask.

sudo ip route add default via 10.24.16.1 dev eth0 onlink

Authoritative References and Official Documentation

Frequently Asked Questions

Quick answers to common questions and configurations

4 FAQs
The legacy ifconfig utility from net-tools communicates with the kernel via ioctl system calls that were designed in the 1990s. It cannot display or manage multiple CIDR addresses on a single interface without awkward alias labels (eth0:0), cannot manage policy routing or multiple routing tables, and scales poorly on hosts with thousands of virtual interfaces. The ip command uses Netlink sockets and supports the entire modern Linux networking stack.
No. Commands like ip addr add, ip link set, and ip route add modify the running kernel's in-memory network state immediately, but they are ephemeral and reset when the system reboots or the network service restarts. To make configurations persistent, add them to your distribution's network manager (Netplan YAML on Ubuntu, nmcli/NetworkManager on RHEL/Rocky, or /etc/network/interfaces on Debian).
The ip command only inspects local kernel network interfaces, so if your machine sits behind a NAT router or cloud internet gateway, ip addr show will only display your private RFC 1918 address (such as 10.x.x.x or 192.168.x.x). To query your external NAT public IP from the terminal, use curl -4 ifconfig.me or dig +short myip.opendns.com @resolver1.opendns.com.
UP is the administrative software flag (IFF_UP) controlled by the administrator via ip link set dev eth0 up. LOWER_UP is the physical or virtual Layer 1 carrier indicator (IFF_LOWER_UP) reported by the NIC driver, meaning an Ethernet cable is plugged into an active switch port or a virtual interface's peer is connected. If an interface shows UP without LOWER_UP, it will also report NO-CARRIER.
RR
Written byVerified Author

Rajesh Ray

I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.

SPAM-FREE MODERATED DISCOURSE

Join the Conversation & Perspective

Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.

AT
MP
JV
+2

No comments on this guide yet. Be the first to share your thoughts or ask a question!

Recommended Reading10 Guides

Related Technical Guides

Tested runbooks, server administration walkthroughs, and troubleshooting guides

Featured Infrastructure PartnerUp to 75% OFF + 3 Months Free

Supercharge Your Linux & Cloud Workloads with Hostinger

Deploy high-speed NVMe KVM VPS, Docker containers, and LiteSpeed-accelerated WordPress servers in under 60 seconds with full root access, dedicated IPv4, and 24/7 technical support.

Pure NVMe SSD StorageFull Root Access & SSHFree Domain & Unlimited SSL99.9% Uptime SLA
Plans from$2.99/mo
Claim Hostinger DealAffiliate link • Special discount applied at checkout