'Unable to start Kestrel. Failed to bind to address address already in use

I want to start a .net core application from an API that I created which is also in .Net Core too.

I added UseUrls() function to Program.cs file so it will use a port that i want it to use. So heres what it looks my Program.cs of that other module.

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

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .UseUrls("http://*:50003")
            .UseKestrel(options =>
            {
                options.Limits.MaxRequestBodySize = null;
            }
            )
            .UseDefaultServiceProvider(options =>
                options.ValidateScopes = false)
            .Build();
}

So when I open CMD where this module where is located and type dotnet run it will start running application on http://localhost:50003, which is fine because thats the port where I want to start.

But what I need to do, is to start this app from that API. And heres the code that I wrote the command dotnet run:

public IActionResult RunPackage(int id)
    {
        try
        {
            var workingDirectory = 'here goes the path of the directory of this module that i want to start running';

            var processStartInfo = new ProcessStartInfo();
            processStartInfo.FileName = "dotnet";
            processStartInfo.Arguments = "run";
            processStartInfo.WorkingDirectory = workingDirectory;
            processStartInfo.UseShellExecute = false;
            processStartInfo.RedirectStandardOutput = true;
            processStartInfo.RedirectStandardError = false;
            processStartInfo.CreateNoWindow = true;
            var process = new Process();
            process.StartInfo = processStartInfo;
            process.Start();
            var reader = process.StandardOutput;
            var output = reader.ReadToEnd();

            return Ok();
        }
        catch (Exception e)
        {
            return BadRequest(e.Message);
        }
    }

But when I'm running it, that output variable returns an error which it says

Unable to start Kestrel.
System.IO.IOException: Failed to bind to address http://127.0.0.1:4221: 
address already in use

And i dont know why it tries to start the app with 4221 port while it is written in Program.cs to use port 50003.

So the same command dotnet run is working fine if i write manually in CMD and its not working the way it should if i type on my code.

"Using launch settings from C:\Users\StarTech\Desktop\Actibook Actibook\actibook-backend\ServerCore\TimeFrame.Actibook.WebService\wwwroot\Packages\2018-6-Friday031203SampleConverter\Properties\launchSettings.json...\r\ncrit: Microsoft.AspNetCore.Server.Kestrel[0]\r\n Unable to start Kestrel.\r\nSystem.IO.IOException: Failed to bind to address http://127.0.0.1:4221: address already in use. ---> Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions.Internal.AddressInUseException: Error -4091 EADDRINUSE address already in use ---> Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.Internal.Networking.UvException: Error -4091 EADDRINUSE address already in use\r\n at Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.Internal.Networking.LibuvFunctions.ThrowError(Int32 statusCode)\r\n at Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.Internal.Networking.LibuvFunctions.tcp_getsockname(UvTcpHandle handle, SockAddr& addr, Int32& namelen)\r\n at Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.Internal.Networking.UvTcpHandle.GetSockIPEndPoint()\r\n at Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.Internal.Listener.ListenTcp(Boolean useFileHandle)\r\n at Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.Internal.Listener.CreateListenSocket()\r\n at Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.Internal.Listener.<>c.b__8_0(Listener listener)\r\n at Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.Internal.LibuvThread.CallbackAdapter1.<>c.<.cctor>b__3_1(Object callback, Object state)\r\n at Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.Internal.LibuvThread.DoPostWork()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.Internal.ListenerPrimary.<StartAsync>d__15.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.LibuvTransport.<BindAsync>d__20.MoveNext()\r\n --- End of inner exception stack trace ---\r\n at Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.LibuvTransport.<BindAsync>d__20.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServer.<>c__DisplayClass23_01.<g__OnBind|0>d.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.AddressBinder.d__5.MoveNext()\r\n --- End of inner exception stack trace ---\r\n at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.AddressBinder.d__5.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.AddressBinder.d__6.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.AddressBinder.d__7.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.AddressBinder.AddressesStrategy.d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.AddressBinder.d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServer.d__23`1.MoveNext()\r\n"

launchSettings.json contanins:

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:60924/",
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "api/values",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "SampleConverter": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "api/values",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "applicationUrl": "http://localhost:60925/"
    }
  }
}


Solution 1:[1]

Does something like this work? It's how my API Was set up a while ago...

  public static IWebHost BuildWebHost(string[] args) =>
     WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .UseKestrel(options =>
            options=>
            {                    
                options.Listen(IPAddress.Any, 50003);
                options.Limits.MaxRequestBodySize = null;
            })
        )
        .UseDefaultServiceProvider(options =>
            options.ValidateScopes = false)
        .Build();

Solution 2:[2]

I also met the error like you and that because I opened 2 terminals and "dotnet watch run" both of them. To solve it, just Ctrl+C to stop the terminal and "dotnet watch run" again in 1 terminal.

Solution 3:[3]

You have to run the following in visual studio command prompt.

dotnet dev-certs https --trust

if you still face the issue, try

dotnet dev-certs https --clean 

and then retry this command

dotnet dev-certs https --trust

Solution 4:[4]

My problem was in a blazor server project, after delete folder AppData.

Solved change target start project in visual studio. Dont know if best way but I had trying lot things without success...

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 GPW
Solution 2 Tiên Nguy?n
Solution 3 sarath chandra
Solution 4 Diego Venâncio