CUBE SUGAR CONTAINER

技術系のこと書きます。

Ubuntu 16.04 LTS の NIC に固定 IP アドレスを振る

たまに設定する機会があると、毎回どうやるんだっけとなって調べるので。

今回使った環境は次の通り。

$ cat /etc/lsb-release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=16.04
DISTRIB_CODENAME=xenial
DISTRIB_DESCRIPTION="Ubuntu 16.04.2 LTS"
$ uname -r
4.4.0-66-generic

NIC は enp9s0 という名前で認識されている。

/etc/network/interfaces を編集する

NIC の設定は /etc/network/interfaces という設定ファイルで行う。 初期設定だと、こんな感じで DHCP を使うようになっていると思う。

$ cat /etc/network/interfaces
# 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 enp9s0
iface enp9s0 inet dhcp

これを、こんな感じにする。 設定方法を静的 (static) にした上で、アドレスとネットマスク、ゲートウェイと DNS サーバを指定する。

$ cat /etc/network/interfaces
# 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 enp9s0
# DHCP はコメントアウトしておくとか
# iface enp9s0 inet dhcp
# 静的アドレスを設定する
iface enp9s0 inet static
address 192.168.0.10
netmask 255.255.255.0
gateway 192.168.0.1
dns-nameservers 192.168.0.1

編集するときはエディタを使っても良いし、例えば今回の編集内容であればこんな感じのコマンドで書き換えても良い。

$ sudo sed -i "/iface enp9s0 inet dhcp/d" /etc/network/interfaces
$ cat << 'EOF' | sudo tee -a /etc/network/interfaces > /dev/null
iface enp9s0 inet static
address 192.168.0.10
netmask 255.255.255.0
gateway 192.168.0.1
dns-nameservers 192.168.0.1
EOF

後は再起動して設定を反映する。

$ sudo shutdown -r now

いじょう。