Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學

Linux 配置多 IP 位址:IP Alias (eth0:1) 與次要 IP 完整設定

編輯:Linux 系統常見問題解答

適用系統

RHEL/CentOS 6/7、Fedora、舊版使用 /etc/sysconfig/network-scripts/ 的發行版。CentOS 8/9、RHEL 8/9、Ubuntu 17.10+ 建議改用 nmcli 或 netplan。

傳統 IP Alias 方式 (eth0:1)

  1. 複製基礎配置
    cp /etc/sysconfig/network-scripts/ifcfg-eth0 \
       /etc/sysconfig/network-scripts/ifcfg-eth0:1
  2. 編輯副本
    vi /etc/sysconfig/network-scripts/ifcfg-eth0:1

    修改關鍵欄位:

    DEVICE=eth0:1
    BOOTPROTO=none
    ONBOOT=yes
    IPADDR=192.168.1.140
    NETMASK=255.255.255.0
    GATEWAY=192.168.1.1   # 僅主介面需設定,alias 通常留空
    HWADDR=00:0C:29:EE:A6:11  # 與主介面相同
    TYPE=Ethernet
    USERCTL=no
    IPV6INIT=no
    PEERDNS=yes
  3. 重啟網路服務生效
    service network restart
    # 或
    systemctl restart network
  4. 驗證
    ip addr show eth0
    # 輸出應包含兩組 inet:192.168.20.140/24 與 192.168.1.140/24

現代 ip 指令臨時新增/刪除(不持久)

# 新增次要 IP
ip addr add 192.168.1.140/24 dev eth0 label eth0:1

# 刪除
ip addr del 192.168.1.140/24 dev eth0

NetworkManager (nmcli) 永久配置(CentOS 7/8、RHEL 7/8 推薦)

# 新增次要 IP 至現有連線
nmcli con mod "System eth0" +ipv4.addresses 192.168.1.140/24
nmcli con up "System eth0"

# 查看
nmcli -f ipv4.addresses con show "System eth0"

Ubuntu Netplan (17.10+) 配置範例 /etc/netplan/01-netcfg.yaml

network:
  version: 2
  renderer: networkd
  ethernets:
    eth0:
      addresses:
        - 192.168.20.140/24
        - 192.168.1.140/24
      gateway4: 192.168.20.1
      nameservers:
        addresses: [8.8.8.8, 1.1.1.1]
netplan apply

注意事項

  • 同一實體介面的多 IP 共用 MAC 位址,屬於 IP Alias,非虛擬介面。
  • 閘道(GATEWAY)僅在主介面設定;次要 IP 無需重複設定。
  • 大量 IP(>100)建議使用 ip route add local 或 CIDR 區塊管理,而非逐一建立 alias 檔案。
Copyright © Windows教程網 All Rights Reserved