Ubuntu 配置网络连接(设置静态 IP 和 DHCP)

Eric 教程 2,986 次浏览 评论已关闭

Ubuntu 配置网络连接有两种方式,在 Ubuntu 17.10 之前通过 ifupdown 配置网络,之后系统版本改用了 Netplan。本文介绍两者配置方法,并包括设置静态 IP 和 DHCP 的示例。

Netplan 配置网络连接(适用 Ubuntu 17.10 及更高版本)

配置文件路径

Netplan 配置文件目录位于 /etc/netplan,默认文件名通常是 50-cloud-init.yaml01-netcfg.yaml

建议做法是删除默认配置文件(避免潜在干扰。也可改后缀名备份),然后根据网卡名称创建配置文件。

先通过 ip addr 命令查询网卡名称,例如下图示例查询红色标注的 ens3 便是。

查询网卡名称

创建网卡配置文件(名称无特别要求,但建议用下面格式)。

sudo vi /etc/netplan/01-ens3.yaml

配置静态 IP 网络

配置内容如下,使用时注意保持内容缩进。里面有几个参数可能新手不知怎样设置,这里补充下。

  • IP 地址使用 CIDR 表示法,它由 IP + 斜杆 + 子网前缀长度 组成(附子网前缀长度换算表);
  • 网关地址通常是子网的第一可用 IP,可通过这个子网计算器查询;
  • 如果网络不支持 IPv6,则去掉其中 IPv6 的相关参数;
# This file describes the network interfaces available on your system
# For more information, see netplan(5).
network:
  version: 2
  renderer: networkd
  ethernets:
    ens3:
      dhcp4: no
      dhcp6: no
      addresses:
        - 192.168.1.2/24
        - "2001:dead:beef::2/64"
      gateway4: 192.168.1.1
      gateway6: "2001:dead:beef::1"
      nameservers:
          addresses: [8.8.8.8, 8.8.4.4]

配置 DHCP 网络

DHCP 模式就简单多了,它会自动获取网络参数而无需手动设置。

# This file describes the network interfaces available on your system
# For more information, see netplan(5).
network:
  version: 2
  renderer: networkd
  ethernets:
    ens3:
      dhcp4: yes
      dhcp6: yes

应用更改生效

sudo netplan apply

如果应用遇到问题,可用下面命令查看错误信息。

sudo netplan --debug apply

ifupdown 配置网络连接(适用 Ubuntu 17.10 往前版本)

配置文件路径

sudo vi /etc/network/interfaces

配置静态 IP 网络

修改其中红色内容换成自己的(依次为网卡名称、IP 地址、子网掩码、网关地址、DNS 服务器)。

# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).

source /etc/network/interfaces.d/*

# The loopback network interface
auto lo
iface lo inet loopback

# The primary network interface
auto ens3
iface ens3 inet static
        address 192.168.1.2
        netmask 255.255.255.0
        gateway 192.168.1.1
        dns-nameservers 8.8.8.8 8.8.4.4

配置 DHCP 网络

# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).

source /etc/network/interfaces.d/*

# The loopback network interface
auto lo
iface lo inet loopback

# The primary network interface
auto ens3
allow-hotplug ens3
iface ens3 inet dhcp

应用更改生效

sudo ip addr flush ens3
sudo systemctl restart networking