58

I'm attempting to create a Web API via .Net Core. I'm just using the boilerplate ValuesController as a Hello World. When I run the project, I get the following error:

System.IO.IOException: "Failed to bind to address https://127.0.0.1:5001: address already in use." ---> System.Exception {Microsoft.AspNetCore.Connections.AddressInUseException}: "Address already in use" ---> System.Exception {System.Net.Sockets.SocketException}: "Address already in use"
  at at System.Net.Sockets.Socket.UpdateStatusAfterSocketErrorAndThrowException(SocketError error, String callerName)\n   at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress)\n   at System.Net.Sockets.Socket.Bind(EndPoint localEP)\n   at Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets.SocketTransport.BindAsync()
  --- End of inner exception stack trace ---
  at at Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets.SocketTransport.BindAsync()\n   at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServer.<>c__DisplayClass22_0`1.<<StartAsync>g__OnBind|0>d.MoveNext()\n--- End of stack trace from previous location where exception was thrown ---\n   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.AddressBinder.BindEndpointAsync(ListenOptions endpoint, AddressBindContext context)
  --- End of inner exception stack trace ---
  at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.AddressBinder.BindEndpointAsync(ListenOptions endpoint, AddressBindContext context)\n   at Microsoft.AspNetCore.Server.Kestrel.Core.LocalhostListenOptions.BindAsync(AddressBindContext context)\n   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.AddressBinder.AddressesStrategy.BindAsync(AddressBindContext context)\n   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.AddressBinder.BindAsync(IServerAddressesFeature addresses, KestrelServerOptions serverOptions, ILogger logger, Func`2 createBinding)\n   at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServer.StartAsync[TContext](IHttpApplication`1 application, CancellationToken cancellationToken)\n   at Microsoft.AspNetCore.Hosting.Internal.WebHost.StartAsync(CancellationToken cancellationToken)\n   at Microsoft.AspNetCore.Hosting.WebHostExtensions.RunAsync(IWebHost host, CancellationToken token, String shutdownMessage)\n   at Microsoft.AspNetCore.Hosting.WebHostExtensions.RunAsync(IWebHost host, CancellationToken token)\n   at Microsoft.AspNetCore.Hosting.WebHostExtensions.Run(IWebHost host)\n   at Sysmex.Unity.Interfaces.WebAPI.Program.Main(String[] args) in /Users/mharrison/Developer/unity-interfaces/Sysmex.Unity.Interfaces.WebAPI/Sysmex.Unity.Interfaces.WebAPI/Program.cs:17

I'm assuming this is just a simple setting problem, but I haven't been able to find anything while Googling. Is there anything that I need to set to allow me to debug the project on Mac OS?

ChickensDontClap
  • 1,871
  • 4
  • 22
  • 39
  • 16
    While this may not be a solution to the underlying problem, a quick fix to get it working again is to execute `kill -9 $(lsof -i:PORT -t) 2> /dev/null`, where PORT is the port that is claimed to be already in use (e.g., 5001) – Ash May 31 '19 at 04:20

15 Answers15

74

Sure you can change the port every time you get that error or even restart your computer, here is the correct way to go about this

Find what is running on that port and kill the process

Terminal on macOS:

Find the process number:

lsof -i: <port number>

e.g.

lsof -i:5001

Then kill the process number:

kill -9 <process number / PID>

e.g.

kill -9 1600
Audwin Oyong
  • 2,247
  • 3
  • 15
  • 32
BitcoinKing
  • 875
  • 7
  • 11
24

I know this is late answer. But it may be helpful to somebody.

There seems a bug with MAC Visual Studio, it always goes https://127.0.0.1/5001.

If you right click on your project, select options. Then Project Options Dialog will appear. On the left pane, goto Run->Configurations->Default, then on the right pane select ASP.Net Core tab. There is App URL which is being used by default. Change it to your needs.

Change IP address in App URL

Amit
  • 2,389
  • 22
  • 29
  • I changed it but still it doesn't work when I change it and then run it it again gives an error and when I check the url is again https://localhost:5001http://localhost:5000 – Nairi Areg Hatspanyan Jun 18 '20 at 15:04
  • @Amit, you saved my day. Works for me! Thanks a lot :) – RuntimeError Oct 27 '20 at 16:17
  • I've changed mine to be different ports in the launchSettings.json and in webBuilder.UseUrls and it STILL uses different ports than what I put in there. – ScubaSteve Mar 22 '21 at 18:24
18

Assuming that you are using default port:

this usually happens when a process gets corrupt and is disconnected from visual studio.

If you are on mac, open activity monitor and kill the process by name "dotnet"

If you are using a non standard port: then you need to change the port number to an available one. There is a solution from Amit on this thread, use that to change the port.

Kalpesh Popat
  • 1,416
  • 14
  • 12
  • 1
    most simple answer and solution. I had two stale dotnet processes when this happened to me. should have far more upvotes. – MSicc Mar 26 '22 at 06:37
12

On Mac, just finding the process and killing it didn't work. We need to kill the process number.

lsof -i: <port number>

e.g.

lsof -i:5001

and kill the process number

kill -9 <process number / PID>

e.g.

kill -9 438

Reason why is that the process using the port was named ControlCenter, which is a native macOS application and it will restart immediately after killing the process.

What finally worked for me was this:

The process running on this port turns out to be an AirPlay server. You can deactivate it in System Preferences › Sharing, and unchecking AirPlay Receiver to release port 5000

Audwin Oyong
  • 2,247
  • 3
  • 15
  • 32
Maja Ozegovic
  • 141
  • 1
  • 6
9

The port 5001 has already used in your system. Change port number to 5002 or whatever you want.

You can add port number with .UseUrls into CreateWebHostBuilder

  public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseUrls("http://localhost:5002")
            .UseStartup<Startup>();

Or if you use visual studio code, just replace args section in .vscode -> launch.json.

"args": ["urls=http://localhost:5002"]
Celal Yildirim
  • 601
  • 1
  • 6
  • 13
9

The port 5001 has already used in your system.

Windows, use task manager to kill the processes "dotnet core host"

Mac, force quit 'dotnet' in Activity Monitor app

enter image description here

Tony Dong
  • 3,213
  • 1
  • 29
  • 32
9

For those who come here because they updated to MacOs Monterey. It has services listening by default on ports 5000 and 7000.

If you are blocked on those ports, running lsof -i tcp:5000 (or 7000) will show something like:

COMMAND   PID USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
ControlCe 371 me   17u  IPv4 0xad81aeb96e1d0669      0t0  TCP *:commplex-main (LISTEN)
ControlCe 371 me   18u  IPv6 0xad81aeb9709a5f91      0t0  TCP *:commplex-main (LISTEN)

For now, you can manually stop the OS from listening on these ports by unchecking AirPlay Receiver in the Apple menu -> System Preferences -> Sharing section.

https://developer.apple.com/forums/thread/682332

BrewsAndDev
  • 121
  • 2
  • 3
6

If you are on Mac, you can find the process running on a port with lsof -i tcp:<PORT>.

To kill the process running on a port, you may try npx kill-port <PORT>

Irshu
  • 8,248
  • 8
  • 53
  • 65
2

Got a similar Error on my project on port 5002 on Visual studio for MAC 2019, restarting Visual studio did nothing.

i shutdown the machine and relaunched

it's a safer solution i think.

Flywings
  • 72
  • 4
2

It seems there is a bug in Visual Studio for Mac. Here is a solution to fix it manually:

1- Open "Run" menu from the top -> "Run with" -> "Custom Configuration". Then go to "ASP.NET Core" tab and copy the "App Url" value. (It's your App's correct port)

2- Now you should paste it inside your project option default run config: in Solution panel, right click on your project and click on "options" -> "Run" -> "Configuration" -> "Default". Then go to "ASP.NET Core" tab and paste the copied value in App Url box.

Now run your project.

ehsanet
  • 21
  • 1
1

I was able to at least temporarily solve this issue by implementing a workaround provided by Bill Boga on his site here: https://www.billbogaiv.com/posts/setting-aspnet-host-address-in-net-core-2

The key for my project was to add .UseUrls(urls: "http://localhost:10000") in the BuildWebHost function. Like so:

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using OrchardCore.Logging;
using OrchardCore.Modules;

namespace ShiftBrandSite
{
    public class Program
    {
        public static void Main(string[] args)
        {
            BuildWebHost(args).Run();
        }

        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseNLogWeb()
                .UseStartup<Startup>()
                .UseUrls(urls: "http://localhost:10000") // <-- localhost urls
                .Build();
    }
}

Hope this helps!

KLPA
  • 199
  • 1
  • 3
0

To complement Amit's answer: Option to change port setting while debugging an ASP.NET Core project in Visual Studio 2019 is as below:

Go to Project Properties > Deubg tab > Web Server Settings > App URL

enter image description here

RBT
  • 24,161
  • 21
  • 159
  • 240
0

My solution was to restart my mac, then it was all good again.

I did not try to kill dotnet from activity monitor but if it will happen again i will give it a try.

miloth
  • 258
  • 3
  • 13
0

Linux Ubuntu Solution:

Just kill the process/port

sudo kill -9 'sudo lsof -t -i:5001'

Might work on MAC as well not sure.

Reza Taba
  • 1,151
  • 11
  • 15
0

Although an old post, when I got this the other day I thought id post my resolution

I could see port it was in the system reserve list using

https://stackoverflow.com/questions/55143246/unable-to-start-kestrel-system-io-ioexception-failed-to-bind-to-address-http

 netsh interface ipv4 show excludedportrange protocol=tcp

so I tried to reserver this port using

netsh int ipv4 remove excludedportrange protocol=tcp startport=5000 numberofports=1

But I got

The error message I get back is: The process cannot access the file because it is being used by another process

I tried all the following

net stop winnat
net stop WwanSvc
net stop LanmanWorkstation
net stop http
net stop W3SVC
iisreset /stop

and I tried killing the application Frame Host and Adobe processes, I even rebooted my pc but still, the error remained.

I eventually worked out it was the process "intel graphics command centre", when I re-installed the dotnet SKD and it failed to install because this process was blocking it. I did not want to have to use another port as .NET has always been on port 5000 and I should not need to alter by builds just to accommodate some other process, I hope this helps someone someday

Patrick Hume
  • 2,064
  • 1
  • 3
  • 11