簡易ルーター+α(CLIによるIPアドレス設定とDHCPサーバー)
転送レベルのみのルーターを、Nano Piで実現する。Nano Piは複数のネットワークI/Fを持つものが多く、ルーター機能を実現しやすい。+αの部分のためのメモであり、どちらかと言えば、Linuxの話となってしまった。
Linux
Nano Piオフィシャルサイトからダウンロードできる、Ubuntuを利用。
I/Fの割り当て
用いたNano Piには、3つのネットワークI/Fがある。
- eth0
- eth1
- eth2
nmcliによる静的IPアドレス設定
大した内容ではない。CLIによるIPアドレス方法の記録。
$ nmcli connection show
NAME UUID TYPE DEVICE
Wired connection 3 164e77e4-5d59-3234-8941-b558c8a88e83 ethernet eth2
Wired connection 1 e922f979-ed4b-3c7e-a3b9-55e2ac1cc71e ethernet --
Wired connection 2 d8299709-9db6-3ff3-89ab-74ac3b3e1560 ethernet --
ネットワークI/F”Wired connection 2”に対して、静的IPアドレスを設定する。
$ sudo nmcli connection modify "Wired connection 2" ipv4.method manual
Error: Failed to modify connection 'Wired connection 2': ipv4.addresses: this property cannot be empty for 'method=manual'
$ sudo nmcli connection modify "Wired connection 2" ipv4.addresses 10.1.2.1/24
$ sudo nmcli connection modify "Wired connection 2" ipv4.method manual
静的化(manual)する前に、IPアドレスを設定する必要があるようだ。
なお、DHCPによるIPアドレス取得がデフォルト。
dnsmasqによるDHCPサーバー
あるネットワークI/Fでは、DHCPサーバーを起動することとし、dnsmasqによる実現が簡単と判断。dnsmasqでは、I/Fが起動(リンクアップ)してからでないと、起動不可であるようだ。調べると、リンクアップすると、”/etc/network/if-up.d”配下にあるスクリプトを起動するようだ。そこで、下記のようなスクリプトを用意。(”chmod +x”などは適宜実行。)
#!/bin/sh
if [ "$IFACE" = eth0 ]; then
echo "eth0 up" >> /tmp/eth0-up.log
dnsmasq --interface=eth0 --except-interface=lo --bind-interfaces --dhcp-option=1,255.255.255.0 --dhcp-option=3,10.1.1.1 --dhcp-range=10.1.1.11,10.1.1.100,12h
fi
環境変数”IFACE”に、ネットワークI/F名が含まれている。
sysctl設定によるルーティング(転送)
カーネルパラメータにて、転送を有効にする。
$ sudo sysctl -w net.ipv4.ip_forward=1
net.ipv4.ip_forward = 1
以上で完成。
おまけ(NAT)
iptablesでNATを実現。過去記事「今さらながらiptables基本(その2)」に基づく。ここでは、eth0及びeth1をNAT内側、eth2をNAT外側にする設定を実施。
$ sudo iptables -t nat -A POSTROUTING -o eth2 -j MASQUERADE
$ sudo iptables -P FORWARD DROP
$ sudo iptables -A FORWARD -i eth0 -o eth2 -j ACCEPT
$ sudo iptables -A FORWARD -i eth1 -o eth2 -j ACCEPT
$ sudo iptables -A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT
EOF