how to get current process listening ports in .net core?

风格不统一 提交于 2020-05-17 09:15:09

问题


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?

I found IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners(), but this will return all tcp listener and without process info.


回答1:


There is a way to get current Address:Port, which i figure out, while starting the project.

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

note:

if try without using environment variable(ASPNETCORE_URLS), you will see empty Addresses collection



来源:https://stackoverflow.com/questions/58931942/how-to-get-current-process-listening-ports-in-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!