NET Core中如何获取当前进程的监听端口? [英] how to get current process listening ports in .net core?
问题描述
创建一个cmd进程并调用 netstat
可能会获得监听端口,但是它很复杂并且创建可能很慢,任何内置方法都可以做到这一点?
create a cmd process and call netstat
may get listening ports, but it's complicated and create may be slowly, any build-in method can does this?
我发现 IPGlobalProperties.GetIPGlobalProperties()。GetActiveTcpListeners()
,但这将返回所有tcp侦听器,而没有进程信息。
I found IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners()
, but this will return all tcp listener and without process info.
推荐答案
有一种方法可以获取当前的 Address:Port
There is a way to get current Address:Port
, which i figure out, while starting the project.
关键点是,您必须至少定义一次 ASPNETCORE_URLS
来自外包源。如果您不这样做,.net核心不会设置DefaultEnpoints
,这会直接导致无法访问的 address:port
。
The critical thing is that you must define at least once 'ASPNETCORE_URLS'
somehow from out-source. If you dont do that .net core doesn't set DefaultEnpoints
which causes unreachable address:port
directly.
Startup.cs
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
String ServerAddress = app.ServerFeatures.Get<IServerAddressesFeature>().Addresses.FirstOrDefault();
Console.WriteLine($"ServerInfo: {ServerAddress}");
...
}
CMD(Windows)
set ASPNETCORE_URLS = http://localhost:2020 && dotnet MyProject.dll
Docker
docker run --rm -it -p 2020:80 -e ASPNETCORE_URLS="http://localhost:2020" MyProjectImage
注意:
如果不尝试使用环境变量(ASPNETCORE_URLS),您将看到空的地址集合
这篇关于NET Core中如何获取当前进程的监听端口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!