258
private void StartReceivingData(string ipAddress, int iPort)
{
    try
    {
        if (!_bContinueReciving)
        {
            //initializeMainSocket(ipAddress, iPort);
            _mSocket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);//<------HERE IS RAISED THE EXCEPTION
            _mSocket.Bind(new IPEndPoint(IPAddress.Parse(ipAddress), iPort));
            //  _mSocket.Bind(new IPEndPoint(IPAddress.Loopback, iPort));
            _mSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, true);
            _mSocket.IOControl(IOControlCode.ReceiveAll, new byte[4] { 1, 0, 0, 0 }, new byte[4] { 0, 0, 0, 0 });
            //var 1
            _mSocket.BeginReceive(_buffReceivedData, 0, _buffReceivedData.Length, SocketFlags.None,
                                 new AsyncCallback(OnReceive), null);
            initializeLocalSocket();
        }
        else
        {
            _bContinueReciving = false;
            _mSocket.Close();
        }
    }
    catch (Exception exception)
    {
        Debug.WriteLine(exception);
    }
}

I'm getting an error when trying to start my program:

An attempt was made to access a socket in a way forbidden by its access permissions.

I don't understand why... it worked fine, and now it doesn't.

I am streaming with VLC, and I want to receive the packets, do some reports, and then restream local to a player.

6
  • 2
    If the exception is happening at the CREATE, the I expect you need to be running as Administrator to create RAW sockets. Mar 22, 2015 at 21:43
  • 1
    Highly related, if not duplicate of An attempt was made to access a socket in a way forbidden by its access permissions
    – Robotnik
    Mar 1, 2016 at 14:24
  • 1
    I have seen a block by the AV with this exception: > 02/01/2017 15:02:18 Blocked by port blocking rule F:\Program > Files\AccessLayers\PortNox\Bin\PortNoxSvc.exe Anti-virus Standard > Protection:Prevent mass mailing worms from sending mail x.x.x.x:25 Jan 2, 2017 at 13:09
  • 1
    try to test by another port that smaller than 10000 Nov 4, 2019 at 12:47
  • 1
    This happened to me when trying to run manually an exe which is a netcore API. It was IIS that holded the port open.
    – Larry
    Mar 24, 2021 at 11:33

25 Answers 25

632

Restarting the Host Network Service on Windows solved the problem.

You can do this with an admin Powershell/ Command Prompt session by running:

net stop hns
net start hns

Or, you can do this using the Windows Services Manager:

services.msc window pane with "Host Network Service" and its associated "Restart" button highlighted

16
  • 2
    After hours of trying to figure out why CaddyServer didn't start anymore with one particular configuration, this was the right solution. Any ideas on why this service can cause such mysterious problems?
    – Chris
    May 11, 2021 at 21:36
  • 12
    do you use docker ? I read somewhere that docker is causing this problem
    – Parsa
    May 12, 2021 at 16:03
  • 50
    worked for me net stop hns && net start hns
    – admin
    Jun 9, 2021 at 0:22
  • 3
    @Parsa thanks man!!! really! I used to do a restart for this to work and reset the tcp/ip stack. Yup, I use docker, it's because of docker. Your solution saved a lot of time from me.
    – Rickless
    Jun 23, 2021 at 11:46
  • 2
    If you have "System error 5 has occurred." when typing these commands, just open your terminal as an administrator (source: lifewire.com/…)
    – programort
    Dec 16, 2021 at 10:35
143

Most likely the socket is held by some process. Use netstat -o to find which one.

10
  • 4
    Sysinternals TCPView can be helpful as well for checking if used by another process (as I just ran into)
    – KornMuffin
    Jan 31, 2014 at 19:14
  • 1
    If the exception were happening at BIND, this would make sense to me. Since it is happening at CREATE, then I expect you need to be Administrator to create RAW sockets. Mar 22, 2015 at 21:44
  • 9
    it's a pity that in my case my app tries to listen on port 62434 BUT checking the listening ports with netstat -o shows that there is not any app currently occupying that port. This is really making me crazy.
    – Hopeless
    Nov 22, 2015 at 19:19
  • 41
    it's actually netstat -ao that includes ports open for listening, or netstat -ano if you want to save up on DNS lookup, or netstat -ano | find ":80" to filter e.g. by port # 80 Sep 25, 2017 at 15:46
  • 13
    It might also be in an excluded range, check with netsh interface ipv4 show excludedportrange protocol=tcp
    – nexus
    Feb 7, 2021 at 5:10
60

Reload Visual Studio with Administrator privileges. Windows Sockets (WinSock) will not allow you to create a SocketType.RAW Socket without Local Admin. And remember that your Solution will need elevated privileges to run as expected!

6
  • 14
    And yet, the accepted answer doesn't explain why the exception happen at the CREATE. it would explain why the exception happened at the BIND. Mar 22, 2015 at 21:45
  • 12
    @pquest - disagree with your comment entirely - this answer is actually very useful and takes care of a certain situation which isn't addressed at all in the main answer . I have upvoted. Jul 17, 2015 at 14:00
  • 4
    There is nothing wrong with answers that address another way a problem can occur, especially with error messages that can be caused by multiple different scenarios
    – Robotnik
    Mar 1, 2016 at 14:24
  • 1
    This is the correct answer to this specific question. In Windows, you have to run programs as Administrator for them to be able to open RAW sockets. The OP is trying to open a RAW socket. Nov 27, 2018 at 20:13
  • In my case, my App was working on localhost good enough, but when deployed in Azure - showed this error. Seeing this answer reminded me that before last deploy I'd started VS without admin rights. After VS start with admin rights and a new Deploy to Azure everything was ok. So, to me, this answer led me to the solution to my problem and the accepted answer was not explanatory enough. Thanks, @Jonathan! Mar 14, 2019 at 16:15
35

Well I don't even understand the culprit of this problem. But in my case the problem is totally different. I've tried running netstat -o or netstat -ab, both show that there is not any app currently listening on port 62434 which is the one my app tries to listen on. So it's really confusing to me.

I just tried thinking of what I had made so that it stopped working (it did work before). Well then I thought of the Internet sharing I made on my Ethernet adapter with a private virtual LAN (using Hyper-v in Windows 10). I just needed to turn off the sharing and it worked just fine again.

Hope this helps someone else having the same issue. And of course if someone could explain this, please add more detail in your own answer or maybe as some comment to my answer.

13
  • 1
    thanks, the internet sharing setting ended up being my problem Dec 12, 2017 at 3:36
  • 4
    using a similar range of ports too, which makes me think perhaps the connection sharing option invisibly uses a few different ranges of ports without reporting it to the netstat tool. Dec 12, 2017 at 3:41
  • 3
    Thank you! For me it turned out to be a VPN connection I had established that was affecting this issue to appear.
    – Gonnagle
    May 15, 2018 at 20:35
  • 3
    Hyper-v had created loads of switches on my PC, removed all but the 2 i used then everything worked as expected again!
    – Peter
    Dec 3, 2018 at 10:20
  • 1
    I had the exact same problem and hyper-v was doing something weird too. Very annoying that netstat didn't uncover anything relating to this. Anyone know why? Mar 14, 2019 at 17:31
28

IIS was the main offender for me. My IIS was running and it restrains any new socket connections from opening. The problem was resolved for me by stopping IIS by running the command "iisreset -stop"

In addition to this, if you use docker, Docker might be the cause of this problem. If so, you have to restart Host Network Service by executing the below command. You may need elevated access to executing this command "net stop hns && net start hns"

13

When a process uses a port, it cannot be used by another process. netstat -o shows the ports being used by a process.

Alternatively, ports can also be excluded from usage. In that case, no process can use them. You can see the list via netsh interface ipv4 show excludedportrange protocol=tcp

5
  • The first time I faced this problem, restarting HNS helped me, the second time, I found the port I used is in reserved ports (and it may differ in different windows) Jun 10, 2022 at 10:41
  • Although this didn't resolve the problem itself, in my case it explained why this error was happening. Now I need to research why this port is in this list, because this used to work with the same port number. Jul 28, 2022 at 12:14
  • @HomayounBehzadian - I had the same issue. It worked for me the first time and suddenly stopped working and it seems to be in exclusion list now Apr 11 at 6:53
  • @TejasPatel you may restart WinNAT service to release reserved ports Apr 11 at 13:23
  • The solution from @Parsa with restarting "Host Network Service" removed the port from the excluded port range. Aug 2 at 8:33
10

I've had this problem when trying to start a dotnet Core project using dotnet run when it tried to bind to the port.

The problem was caused by having a Visual Studio 2017 instance running with the project open - I'd previously started the project via VS for debugging and it appears that it was holding on to the port, even though debugging had finished and the application appeared closed.

Closing the Visual Studio instance and running "dotnet run" again solved the problem.

1
  • This did it for me. I will add that you can have both open at the same time, as long as you never run it from Vis. Like Gareth says, if you debug it in Vis it will hold onto that port even after stopping the process.
    – MDMoore313
    Jul 3, 2020 at 3:01
9

I had a similar problem but I fixed it by doing some changes in the firewall setting.

You can follow the below steps

  1. Go to "Start" --> "Control Panel"

  2. Click on "Windows Firewall" enter image description here

  3. Inside Windows Firewall, click on "Allow a program or feature through Windows Firewall" enter image description here

  4. Now inside of Allow Programs, Click on the "Change Settings" button. Once you click on the Change Settings button, the "Allow another program..." button gets enabled. enter image description here

  5. When you click on the "Allow another program..." button, a new dialog box will appear. Choose the programs or applications for which you are getting the socket exception and click on the "Add" button.

enter image description here

  1. Click OK, and restart your machine.

  2. Try to run your application (which has an exception) with administrative rights.

I hope this helps.

1
  • In my case, I was using tinywall that blocked app. May 19, 2022 at 16:00
5

This is the error that is returned when the Windows Firewall blocks the port (out-going). We have a strict web server so the outgoing ports are blocked by default. All I had to do was to create a rule to allow the TCP port number in wf.msc.

5

Run the terminal as an administrator then run this :

net stop hns
net start hns
4

I'm developing a UWP application which connects to an MQTT broker in the LAN. I got a similar error.

MQTTnet.Exceptions.MqttCommunicationException: 'An attempt was made to access a socket in a way forbidden by its access permissions [::ffff:xxx.xxx.xxx.xxx]:1883'

ExtendedSocketException: An attempt was made to access a socket in a way forbidden by its access permissions [::ffff:xxx.xxx.xxx.xxx]:1883

Turned out that I forgot to give the app the correct capabilities ... enter image description here

1
4

The reason is most likely due to a Windows Update that restricted access to certain ports on Windows machines. You can view a list of which ports are excluded from your user by running this command:netsh interface ipv4 show excludedportrange protocol=tcp

In my case after changing my ports, everything works fine.

3

I ran into this in a Web App on Azure when attempting to connect to Blob Storage. The problem turned out to be that I had missed deploying a connection string for the blob storage so it was still pointing at the storage emulator. There must be some retry logic built into the client because I saw about 3 attempts. The /devstorageaccount1 here is a dead giveaway.

enter image description here

Fixed by properly setting the connection string in Azure.

1
  • You are simply amazing
    – killexe
    May 4, 2022 at 12:11
3

I solved simply stopping the installed version of the service that was running in the machine using the same port.

Alternatively, run the debug instance with a different port.

3

I just ran into this myself, found the cause after reading this post:

https://ardalis.com/attempt-made-to-access-socket/

in short when I used the command:

netsh interface ipv4 show excludedportrange protocol=tcp

it showed the port I was trying to use was reserved; so I just picked another port (one which was not reserved) and it worked.

1
  • 1
    Thanks for this, completely unknown to me, but sure enough the port I was attempting to use was within an excluded range.
    – hlovdal
    Jul 26 at 11:01
2

As noted by Gonnagle, this can be caused by having an installed VPN client in the connected state. For us, disconnecting from the VPN resolved the issue.

1

Running iisreset in a command window fixed it for me.

1

I had the same error happening when I had two different ASP.net projects in two different Visual Studio instances.
Closing one of them fixed the issue.

1

I've just had a similar problem, from a Xamarin Forms application, which was making an outbound call to Azure via HttpClient.

In my case the root cause of the problem turned out to be my security suite, BitDefender, blocking outbound access for my application, because it thought it was a threat.

I've added an exception to the firewall for this application and it has solved the problem.

1

I tried everything suggested by others: port wasn't already used, with admin rights I had the same error, tried with cygwin and wsl without any success. I finally make it start using a port > 5000, such as 5050, no admin rights are necessary now.

0

I got this error because my ASP.NET Core app listens on ports 80/443 for Release builds and other ports for Debug builds. Of course using netstat on the Debug build ports showed the ports were not in use which is why I was so confused. Ports 80/443 are obviously going to be used by something else on your machine so just make sure you are not trying to use those ports, otherwise you'll get the same error message and nothing else will help you!

0

For me it was cause of network adapters such as Vmware, TAP disabling these solved it. Solution

0

Open IIS (Run As Administrator) --> Go to Sites --> Default Sites --> Bindings --> Check the extra port if found then remove them.

After this restart your IIS Server by clicking on the Restart button:

Image Link

0

This is annoyingly a fairly common problem in .NET Core or .NET 5+ web apps, usually those that are trying to run https (SSL). A quick and dirty work around that doesn't require restarting IIS is to change your port in your launchSetting.json. Keep in mind that this is probably just a problem on your PC so you may not want to check in this change into your Source Control.

launchSettings.json

-1

First, press win+R to open the Run dialog, then type CMD and simultaneously press Ctrl+Shift+Enter to ensure you're opening the Command Prompt as an administrator.

Next, input 'netstat -aon|findstr "8080"' to check which process is using port 8080.

Then, use 'taskkill /pid 4 -t -f' to terminate the process. If you encounter difficulty terminating PID 136 (which belongs to a subprocess of PID 4), the error message 'Access Denied' might be the reason.

Finally, input 'net stop http', and when prompted, enter 'Y' to free up port 8080 for re-use. enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.