我发现我的Windows 10电脑上有一些端口既没有被进程使用,也无法监听。我发现这个问题是在尝试运行一个占用3000端口的节点服务器时发现的。我在这个主题上找到了许多相关问题,例如Node.js Port 3000 already in use but it actually isn't?。所有这些问题的回答者都建议使用"netstat -ano"查找使用该端口的进程并将其停止。但事实上,我发现有很多端口被阻止了,并未与进程绑定,这与杀毒软件和防火墙均无关,因为我关闭了防火墙,只开启了Windows Defender杀毒软件。我编写了一个程序来监听127.0.0.1上从3000到5000的所有端口。
该程序产生的输出类似于以下内容...
我发现在3000至5000的范围内,有624个端口被阻止了。而“netstat -ano”显示该范围内只使用了5个端口。那么是什么阻止了剩下的619个端口呢?
int port = 3000;
while(port <= 5001)
{
try
{
ListenOnPort(port);
++port;
}
catch (Exception ex)
{
Console.WriteLine($"Listen on {port} failed: {ex.Message}");
++port;
}
}
Where ListenOnPort is...
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个端口呢?
socket()
、bind()
和close()
来替换它们。 - user207421