Ubuntu 上通过以太网分享网络连接(NAT)

Ubuntu 自带网络分享功能,但该功能很不稳定,往往断开连接后再连就无法使用了。
现在我们使用 DNSMASQ+IPTables 手动配置NAT.

禁用 systemd-resolved

Ubuntu 提供的 systemd-resolved 抢占53端口,首先禁用它。

  1. systemctl stop systemd-resolved
  2. systemctl disable systemd-resolved

删除不当设置

如果你之前配置过网络分享或已经用有线连接过电脑了,则需要这一步
运行 nm-connection-editor
删除所有有关你要分享的网卡的设置

安装并配置DNSMASQ

安装

  1. apt install dnsmasq
  2. service dnsmasq stop
  3. nano /etc/dnsmasq.conf

编辑 /etc/dnsmasq.conf,加入下列内容:

  1. dns-forward-max=15000
  2. #eno1为你的要分享的网卡名
  3. interface=eno1
  4. dhcp-range=192.168.33.2,192.168.33.150,255.255.255.0,12h

配置域名解析

  1. nano /etc/resolv.conf

填写你的DNS服务器,例如:

  1. nameserver 223.5.5.5
  2. nameserver 223.6.6.6
  3. nameserver 114.114.114.114

启用内核IPV4转发

  1. /etc/sysctl.conf

加入:

  1. net.ipv4.ip_forward=1

运行:

  1. sysctl -p

配置转发,为网卡分配初始IP

eno1为你的要分享的网卡名
enp2s0为有网的(被分享的)网卡名

  1. ifconfig eno1 192.168.33.2
  2. iptables -t nat -A POSTROUTING -o enp2s0 -j MASQUERADE
  3. iptables -A FORWARD -i eno1 -o enp2s0 -m state --state RELATED,ESTABLISHED -j ACCEPT

上述内容重启后无效,可加入 /etc/rc.local 以开机自动应用。

启动DNSMASQ

  1. systemctl enable dnsmasq
  2. systemctl start dnsmasq
  3. systemctl status dnsmasq

完事!


0  字
评论