继续创造,加快成长!这是我参加「掘金日新方案 10 月更文应战」的第4天,点击检查活动详情

众所周知,如果咱们在起一个本地 http 服务,然后就能够在浏览器中经过 localhost 或 127.0.0.1 来拜访了。而经过 localhost 域名就能拜访本地 http 服务的原因是在 /etc/hosts 文件中做了映射:

$ cat /etc/hosts
##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting.  Do not change this entry.
##
127.0.0.1	localhost
255.255.255.255	broadcasthost
::1             localhost

那你有没有想过:如果把 /etc/hosts 中的映射给注释掉,localhost 还能拜访通吗?

这个我就不给出答案了,我们动手自行测验一下,有许多办法能够发动本地服务器,如果你的电脑上装置了 Python3 的话,最简单办法:

$ python3 -m http.server
Serving HTTP on :: port 8000 (http://[::]:8000/) ...

如果只装置了 Python2 则能够用下面的命令:

$ python -m SimpleHTTPServer 8080
Serving HTTP on 0.0.0.0 port 8080

如果没装置 Python,可是有 Node.js 环境的话,能够用下面的命令:

$ node -e "require('http').createServer((req, res) => res.end('Hello World')).listen(8080)"

验证之后无妨考虑一下成果为什么是这样呢?localhost 这个字符串究竟是什么魔法?ping 一下 localhost 会得到什么成果?

别的,咱们也知道,如果有两台电脑的话,只需连在相同的局域网下面,在其中一台上发动本地 http 服务,在别的一台上也能够经过 ip 来拜访这个服务。那咱们就来测试一下在 A 电脑上发动本地服务,在 B 电脑上拜访,首先在检查 A 电脑的本机 IP:

$ ifconfig en0
en0: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500
	options=6463<RXCSUM,TXCSUM,TSO4,TSO6,CHANNEL_IO,PARTIAL_CSUM,ZEROINVERT_CSUM>
	ether 14:7d:da:cd:ea:80
	inet6 fe80::d8:4e6d:37ef:fdf0%en0 prefixlen 64 secured scopeid 0x6
	inet 192.168.31.83 netmask 0xffffff00 broadcast 192.168.31.255
	nd6 options=201<PERFORMNUD,DAD>
	media: autoselect
	status: active

然后在电脑 B 上拜访 http://192.168.31.83:8080 ,就能够恳求到数据了,这没什么好说的。那如果咱们在 B 电脑上修改了 localhost 的映射,将 localhost 映射到 192.168.31.185,你猜会是什么效果呢?

192.168.31.185	localhost

经过实际验证发现在 Safari 上面能正常拜访 A 电脑的服务,可是 Chrome 上面会不识别,报错如下:

记修改 hosts 文件中 localhost 映射的一次探索

然后又测验了 Firefox,发现也是报错的:

记修改 hosts 文件中 localhost 映射的一次探索

后来网上搜了一下,找到一个 stackoverflow 的回答,顺藤摸瓜找到源码,发现只需是 localhost 字符串或许以 .localhost 结尾的都被视为环回地址(loopback)。

记修改 hosts 文件中 localhost 映射的一次探索

估计 Firefox 的逻辑也是类似的,所以能够使用其他字符串做映射,别用 localhost 啦。本实验到此结束,虽然看起来很无厘头,可是还是学到了不少东西,技能都是探索出来哒!