我发现Windows 10机箱上有许多端口,其中(1)未被任何进程使用,(2)我无法监听。
我在尝试运行使用端口3000的节点服务器时发现了此问题。我发现了有关此主题的许多问题。这是典型的:Node.js Port 3000 already in use but it actually isn't?
所有对此问题和类似问题的答复者都建议使用“ netstat -ano”来查找正在使用该端口并杀死它的进程。
我发现的是,有大量被阻塞的端口与进程无关。这与AV或防火墙无关。我关闭了防火墙,只有Windows Defender AV。
我编写了一个程序来侦听127.0.0.1上的3000到5000之间的端口。
int port = 3000;
while(port <= 5001)
{
try
{
ListenOnPort(port);
++port;
}
catch (Exception ex)
{
Console.WriteLine($"Listen on {port} failed: {ex.Message}");
++port;
}
}
ListenOnPort在哪里...
private static void ListenOnPort(int v)
{
var uri = new UriBuilder("http", "127.0.0.1", v);
HttpListener listener = new HttpListener();
listener.Prefixes.Add(uri.Uri.ToString());
Console.WriteLine($"Listening on {v}");
listener.TimeoutManager.IdleConnection = new TimeSpan(0, 0, 1);
listener.Start();
var task = listener.GetContextAsync();
if(task.Wait(new TimeSpan(0,0,1)))
{
HttpListenerResponse response = task.Result.Response;
// Construct a response.
string responseString = "<HTML><BODY> Hello world!</BODY></HTML>";
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
// Get a response stream and write the response to it.
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
// You must close the output stream.
output.Close();
}
listener.Stop();
}
程序产生的输出与此类似...
Listening on 3000
Listen on 3000 failed: The process cannot access the file because it is being used by another process
Listening on 3001
Listen on 3001 failed: The process cannot access the file because it is being used by another process
Listening on 3002
Listen on 3002 failed: The process cannot access the file because it is being used by another process
Listening on 3003
Listen on 3003 failed: The process cannot access the file because it is being used by another process
Listening on 3004
Listen on 3004 failed: The process cannot access the file because it is being used by another process
Listening on 3005
Listen on 3005 failed: The process cannot access the file because it is being used by another process
Listening on 3006
Listening on 3007
Listening on 3008
Listening on 3009
Listening on 3010
我发现在3000到5000之间,有624个端口被阻塞。同时,“ netstat -ano”显示该范围内正好有5个端口在使用。那么是什么阻塞了其他619个端口?
答案 0 :(得分:3)
右...
在寻找其他东西时,我找到了答案(至少是问题的根源)。我无法连接到这些端口的原因是,它们都是Windows上排除的端口范围的一部分。要查看排除的端口,请使用...
$ netsh int ipv4 show excludedportrange tcp
神奇的是,这里列出了我无法连接的所有端口。这些排除的端口范围显然源自我已经安装的HyperV和Docker。显然有一种方法可以将端口找回...这并不容易,因为它涉及到卸载Docker和HyperV,然后为自己保留端口范围,然后重新安装HyperV和Docker。不值得。既然我已经知道如何找到无法使用的端口,那么我将不再使用它们!