You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

移除Windows与WSL hosts文件中localhost映射后仍可访问本地服务的问题求助

移除Windows与WSL hosts文件中localhost映射后仍可访问本地服务的问题求助

大家好,我遇到了一个百思不得其解的问题,想请教下各位开发者:

我目前使用**WSL(Ubuntu 22.04)**作为开发环境,通过VS Code连接WSL进行开发工作。我写了一个简单的Express Web服务,代码如下:

import express from 'express';

const app = express();

app.get('/', (req, res) => {
  res.cookie('state', 'ok', { httpOnly: true });
  res.sendStatus(200);
});

app.listen(3000, () => {
  console.log('Listening on port 3000');
});

为了测试localhost的解析行为,我把Windows系统中C:\Windows\System32\drivers\etc\hosts文件里的localhost相关映射全部注释掉了,当前hosts文件内容如下:

# localhost name resolution is handled within DNS itself.
# 127.0.0.1 localhost
# ::1       localhost

同时我也把WSL内/etc/hosts文件里的localhost相关记录全部注释掉了,文件内容如下:

# This file was automatically generated by WSL. To stop automatic generation of this file, add the following entry to /etc/wsl.conf:
# [network]
# generateHosts = false
#127.0.0.1      localhost
# 127.0.1.1     LAPTOP-C8AFGSGK.        LAPTOP-C8AFGSGK
# 127.0.0.1     localhost
# 127.0.0.1       api.example.com
# The following lines are desirable for IPv6 capable hosts
#::1     ip6-localhost ip6-loopback
#fe00::0 ip6-localnet
#ff00::0 ip6-mcastprefix
#ff02::1 ip6-allnodes
#ff02::2 ip6-allrouters

按我的预期,此时localhost应该没有对应的IP映射,浏览器访问http://localhost:3000应该无法连接到服务才对,但实际情况是依然能正常访问并拿到响应。我用Edge浏览器的edge://net-internals/#dns工具查询localhost的解析结果,显示:

Resolved IP addresses of "localhost": ["::1","127.0.0.1"].
No data on which protocols are supported.

看起来localhost还是会被解析到127.0.0.1和::1。我的预期是只有直接访问http://127.0.0.1:3000才能连通服务,localhost应该无法访问。请问我是不是漏掉了什么系统层面的默认配置或者规则?

备注:内容来源于stack exchange,提问作者Lin Du

火山引擎 最新活动