Cannot open port 2000 on 127.0.0.1 adapter - how to find the reason?

1

For months I haven't run a .NET application we develop, which worked fine last time around. In the meantime, I've updated my computer to Windows 10 Pro 1809 (as well as at home).

Today I tried running it, and it wasn't behaving properly. I debugged it and narrowed it down to an exception after the code attempts to start a TCP server on a configurable port, which is by default 2000.

The exception is the following:

System.Net.Sockets.SocketException (0x80004005): An attempt was made to access a socket in a way forbidden by its access permissions

It is thrown when this code is executed:

        listener = new TcpListener("127.0.0.1", 2000);
        listener.Start();

I did the normal diagnostic steps, to no avail:

  • Is anything already listening on that port
  • Disable firewall
  • Re-enable the firewall then delete rules surrounding the application and the port in question
  • Enable firewall logging to see if there's any evidence of it rejecting

So I quickly test the same in a PowerShell script:

$port = 2000
$listener = new-object System.Net.Sockets.TcpListener ("127.0.0.1", $port)
try 
{
    $listener.start()    
    Write-Output "Successfully opened port $port"
}
catch 
{
    Write-Error $_          
}
finally
{
    $listener.Stop()
}

And I get pretty much the same exception: Exception calling "Start" with "0" argument(s): "An attempt was made to access a socket in a way forbidden by its access permissions"

Next I decide to change the port to 3000 and it works fine.

Next I adapt the script to loop between ports from 1 to 2500 and get a bunch of failures, including ranges from 1657 to 2156 and 2179 to 2279.

Where would one go next to find the root cause? What mechanism could Windows be using to reject the binding (?) attempt?

UPDATE

Tried this C# application and I get the same result:

namespace TcpBindTest
{
    using System.Net;
    using System.Net.Sockets;

    class Program
    {
        static void Main(string[] args)
        {
            Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint endpoint = new IPEndPoint(new IPAddress(new byte[]{127, 0, 0, 1}), 2000);
            listener.Bind(endpoint);
            listener.Listen(1);
        }
    }
}
c#
windows
powershell
tcp
tcplistener
asked on Stack Overflow Mar 22, 2019 by johnildergleidisson • edited Mar 23, 2019 by mklement0

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0