Hourglass
Hourglass

Reputation: 172

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

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.

Upvotes: 0

Views: 1238

Answers (1)

Mustafa Salih ASLIM
Mustafa Salih ASLIM

Reputation: 713

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

Upvotes: 1

Related Questions