Skip to main content

指令比較:ifconfig vs ip

在 Linux 系統中,管理和查詢網路介面設定是最常見的操作之一。過去我們習慣使用 ifconfig,但在現代 Linux 發行版中,ip 指令已經成為標準的替代方案。

1. 基本差異與背景

特性ifconfigip
所屬套件net-toolsiproute2
狀態已過時 (Deprecated)現代標準 (Modern Standard)
核心介面使用較舊的 ioctl 系統呼叫使用較新、效能更好的 netlink 通訊端
功能範圍主要針對網路介面 (IP 網址、MAC、MTU 等)功能全面 (包含介面、路由、ARP 快取、Tunnel、Network Namespace 等)

ifconfig 長期以來是管理網路的標準工具,但因其架構限制與缺乏新層級網路技術的支援,在多數現代 Linux 發行版 (如 CentOS 7+, Ubuntu 18.04+, Debian) 中已經被棄用甚至預設不予安裝,取而代之的是功能更強大的 iproute2 工具集中的 ip 指令。

2. 常用指令對照表

如果你已經熟悉 ifconfig,可以透過以下對照表快速學習 ip 的同等操作:

查詢網路資訊

任務ifconfig (與舊版套件)ip 指令
顯示所有啟用的介面ifconfigip addr show 或縮寫 ip a
顯示所有介面 (含已關閉)ifconfig -aip link show 或縮寫 ip l
顯示特定介面 (如 eth0)ifconfig eth0ip addr show eth0ip a show dev eth0
顯示介面統計資訊ifconfig eth0ip -s link show eth0

修改網路設定

任務ifconfigip 指令
啟用介面 (Up)ifconfig eth0 upip link set eth0 up
停用介面 (Down)ifconfig eth0 downip link set eth0 down
設定 IP 與遮罩ifconfig eth0 192.168.1.10 netmask 255.255.255.0ip addr add 192.168.1.10/24 dev eth0
移除 IP 設定通常使用 ifconfig eth0 0ip addr del 192.168.1.10/24 dev eth0
清除介面所有 IP無直接指令ip addr flush dev eth0
修改 MAC 位址ifconfig eth0 hw ether 00:11:22:33:44:55ip link set dev eth0 address 00:11:22:33:44:55

路由與 ARP (搭配其他 net-tools 工具)

以往我們會用到 routearp 指令,現在都可以整合到 ip 中呼叫:

任務舊版工具 net-toolsip 指令
顯示路由表route -nip route showip r
新增預設閘道route add default gw 192.168.1.1ip route add default via 192.168.1.1
顯示 ARP 快取表arp -anip neigh showip n

3. 為什麼要改用 ip 指令?

  1. 功能更強大:除了基本的 IP 設定之外,ip 指令可以設定 Policy Routing (策略路由)、建置 Tunnel 工具、處理 Network Namespace,這些都是 Docker 和 Kubernetes 等雲端原生技術底層依賴的網路功能 (ifconfig 無法做到)。
  2. 輸出更好解析ip 提供了 JSON 格式輸出的選項 (例如 ip -j a),在撰寫腳本和自動化維運時非常好用。
  3. 一致性的語法ip 指令的語法採用 ip [OPTIONS] OBJECT [COMMAND] 的邏輯 (例如:ip addr showip route add),架構分明,相較於 ifconfig 大雜燴的寫法更容易記憶與擴展。

總結:雖然老派的 Linux 使用者可能對 ifconfig 依賴甚深,但擁抱 ip 指令絕對是現代 Linux 系統管理與容器化技術的必備技能。

4. 補充:在 macOS 上沒有 ip 指令?

如果你在 Mac 的終端機(Terminal 或 iTerm2)上輸入 ip aip,可能會出現 command not found: ip

zsh: command not found: ip

這是因為 ip 指令(iproute2 套件)是 Linux 專屬的工具

macOS 的底層是基於 BSD 作業系統,而不是 Linux。在 BSD 系統(包含 macOS、FreeBSD 等)中,網路設定依然維持使用傳統的工具:

  • 查看或設定網路介面:ifconfig
  • 查看路由:netstat -nrroute
  • 查看 ARP 表:arp -an

解決方案:

  1. 直接使用 ifconfig:在 macOS 開發或日常使用上,習慣使用 ifconfig 即可。
  2. 安裝 iproute2mac (如果你真的想在 Mac 上用 ip): 可以透過 Homebrew 安裝一個名為 iproute2mac 的 Python 封裝工具,它會把 ip 指令的語法轉換成 macOS 系統認得的 ifconfig/route 指令。
    brew install iproute2mac
    安裝後,你就可以在 Mac 上快樂地使用 ip aip r 了。