一、 问题来源
有时我们需要在工作网络环境下,为了和同事进行协同,或者互相之间有需要进行各自电脑的资源共享(更多的是为了在局域网下协作方便,互相需要知道彼此的IP地址),并防止IP地址冲突造成网络的时断时续无法上网问题,我们希望固定我们的电脑的IP地址。
二、解决办法
- 搜索了很多网上的解决办法,看到有很多都是修改或编辑 /etc/network/interfaces 文件,如下:
可以看到 192.168.16.178 就是我想要固定的IP地址,但是当我重启电脑或我第二天上班开机的时候发现它又变了,而且是我之前固定一个IP:192.168.16.119,但是119这个貌似已经和别的电脑IP冲突了,所以我上网时断时续无法上网。luoxi@luoxi-linux:~$ cat /etc/network/interfaces # interfaces(5) file used by ifup(8) and ifdown(8) auto lo iface lo inet loopback auto enp1s0 iface enp1s0 inet static address 192.168.16.178 netmask 255.255.255.0 gateway 192.168.16.1 ns-nameserver 172.16.1.4
- 接着,我在想既然每次重启或开机都是 119这个IP,肯定是哪里给固定了,而且我需要去手动改掉它,最后我搜索到了这个工具:netplan, 很好ubuntu 16 和 18 都带有这个工具,然后怎么做呢,看下面:
首先看下网卡信息:
接下来,我们看下netplan -h:enp1s0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet 192.168.16.178 netmask 255.255.255.0 broadcast 192.168.16.255 inet6 fe80::8eec:4bff:fe6a:1c62 prefixlen 64 scopeid 0x20<link> ether 8c:ec:4b:6a:1c:62 txqueuelen 1000 (以太网) RX packets 235831 bytes 225411841 (225.4 MB) RX errors 0 dropped 2 overruns 0 frame 0 TX packets 161560 bytes 22774156 (22.7 MB) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
可以看到 generate 下有 /etc/netplan/*.yaml, 这个就是我们要找的地方,我的配置如下:luoxi@luoxi-linux:~$ netplan -h usage: /usr/sbin/netplan [-h] [--debug] ... Network configuration in YAML optional arguments: -h, --help show this help message and exit --debug Enable debug messages Available commands: help Show this help message apply Apply current netplan config to running system generate Generate backend specific configuration files from /etc/netplan/*.yaml ip Retrieve IP information from the system try Try to apply a new netplan config to running system, with automatic rollback
最后,按上面的方法结合你的具体网卡信息,修改好 *.yaml 配置文件保存,然后执行命令 netplan apply 即可完成固定IP的效果。重启电脑生效!luoxi@luoxi-linux:~$ cat /etc/netplan/50-cloud-init.yaml network: ethernets: enp1s0: addresses: - 192.168.16.178/24 gateway4: 192.168.16.1 nameservers: addresses: [172.16.1.14, 172.16.1.228] dhcp4: false optional: false version: 2
三、其他
- 如果按上述方法未生效,请参考更多的 netplan 固定ip地址的设置方法,并详细检查配置的dns, 网关等 ip是否正确;
- 50-cloud-init.yaml 的配置文件文件名只是我的配置文件名,请根据自己的Ubuntu或linux其他版本查看具体文件并配置生效,灵活变通。
- 未有面面俱到,有问题可留言,谢谢!