253
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.

zcoop98
  • 2,590
  • 1
  • 18
  • 31
andrew
  • 2,797
  • 3
  • 18
  • 16
  • 2
    If the exception is happening at the CREATE, the I expect you need to be running as Administrator to create RAW sockets. – Jesse Chisholm Mar 22 '15 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](http://stackoverflow.com/questions/4799651/an-attempt-was-made-to-access-a-socket-in-a-way-forbidden-by-its-access-permissi) – Robotnik Mar 01 '16 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 – user7365403 Jan 02 '17 at 13:09
  • 1
    try to test by another port that smaller than 10000 – Behzad Ebrahimi Nov 04 '19 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 '21 at 11:33
  • 1
    It just means the port is in use. Either kill whatever is holding the port open, or pick another port. – Liam Feb 18 '22 at 17:14

25 Answers25

620

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

zcoop98
  • 2,590
  • 1
  • 18
  • 31
Parsa
  • 7,995
  • 2
  • 27
  • 37
  • 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 '21 at 21:36
  • 11
    do you use docker ? I read somewhere that docker is causing this problem – Parsa May 12 '21 at 16:03
  • 50
    worked for me `net stop hns && net start hns` – admin Jun 09 '21 at 00: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 '21 at 11:46
  • 2
    If you have "System error 5 has occurred." when typing these commands, just open your terminal as an administrator (source: https://www.lifewire.com/how-to-fix-system-error-5-has-occurred-on-windows-4770868) – programort Dec 16 '21 at 10:35
  • 1
    I had this problem with a Golang program, tried this start/stop and, behold, it worked. Why? I have no idea - it worked fine yesterday (I did a reboot in the meantime, though). – WoJ Jan 11 '22 at 12:58
  • 1
    Thanks, it worked! I had this problem with MySQL. I also have docker on my machine but wasn't running anything in it at the time... – Dan Manastireanu Jan 17 '22 at 07:29
  • 1
    scoop install sudo and then sudo net stop hns && sudo net start hns :) – Dawid Gosławski Apr 06 '22 at 08:49
  • 1
    When using docker and wampserver on the same machine, this error happens some times. Just mentioning if somebody had the same problem like me, it solves it, thanks. :-) – Aarony Apr 16 '22 at 15:45
  • 1
    Worked for me, no Docker involved at all on my machine – Lennart Jul 25 '22 at 06:31
  • 1
    Worked on my long-standing socket ::bind problem. Anybody know how to start and stop the `hns` programmatically? – rtischer8277 Aug 11 '22 at 15:28
  • 1
    "Anybody know how to start and stop the hns programmatically?" No need to do that. For windows, when exiting a program that has this problem, don't use `ExitProcess()` or `exit()`. Use `TerminateProcess(...)` which is guaranteed to exit all threads. – rtischer8277 Aug 18 '22 at 15:28
  • 1
    Worked for me too got the error binding to 5001 using a net core app. – Ian Jowett Dec 19 '22 at 10:21
  • 1
    Restarting the Host Network Service with Windows Services Manager fixed it for me, thank you so much!! – Amélie Dupré Jul 05 '23 at 10:17
  • 1
    Worked for me and solved the problem by using the ps commands for restart. Thank you! – Ross Aug 18 '23 at 08:21
141

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

stark
  • 12,615
  • 3
  • 33
  • 50
  • 4
    Sysinternals [TCPView](http://technet.microsoft.com/en-us/sysinternals/bb897437.aspx) can be helpful as well for checking if used by another process (as I just ran into) – KornMuffin Jan 31 '14 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. – Jesse Chisholm Mar 22 '15 at 21:44
  • I've only ever seen this error at bind. Here's an example: http://help.octopusdeploy.com/discussions/problems/22665-an-attempt-was-made-to-access-a-socket-in-a-way-forbidden-by-its-access-permissions – stark Mar 23 '15 at 19:32
  • 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 '15 at 19:19
  • 1
    Are you running a firewall or iptables rules that block the port? Also, what user is your app running as? – stark Nov 22 '15 at 20:51
  • 39
    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 – Arthur Stankevich Sep 25 '17 at 15:46
  • In my example, I try to run on 80 port and default web site was using this. When I stopped the web site and rerun kestrel, the problem was resolved. – ddagsan Nov 06 '18 at 06:10
  • 13
    It might also be in an excluded range, check with `netsh interface ipv4 show excludedportrange protocol=tcp` – nexus Feb 07 '21 at 05:10
  • For me the culprit was `iphlpsvc` - the ports were ones that I had bound to on docker (running Rancher desktop). It also had a dependent service that had to be stopped , but `Restart-Service iphlpsvc` in powershell did the trick. `Get-Service iphlpsvc -DependentServices` to see what you need to stop, if you get an error about dependent services. – Kimvais Nov 30 '22 at 10:50
  • For me, I forgot that I recently installed another application that exposed services on the port I was trying to use. – gwruck Jan 24 '23 at 21:05
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!

Jonathan
  • 627
  • 5
  • 2
  • 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. – Jesse Chisholm Mar 22 '15 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. – James Harcourt Jul 17 '15 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 01 '16 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. – Hank Schultz Nov 27 '18 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! – Kalin Krastev Mar 14 '19 at 16:15
  • I just shut down visual studio and then reopened it and it worked! – R.P. May 19 '22 at 16:08
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.

Hopeless
  • 4,397
  • 5
  • 37
  • 64
  • 1
    thanks, the internet sharing setting ended up being my problem – kellpossible Dec 12 '17 at 03: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. – kellpossible Dec 12 '17 at 03: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 '18 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 03 '18 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? – Ross Ellerington Mar 14 '19 at 17:31
  • `netstat -ano` shows that port `1234` isn't used by anything, yet I cannot connect to that port, I suspect it might be related to Hyper-V, but after reading your answer, I'm still not clear on what I'm supposed to do in Windows 10. Can you elaborate for us n00bs please? – J86 Oct 18 '19 at 19:51
  • @J86 I'm not sure if your issue is similar to what I had, I clearly said what I did: `turn off the sharing` - try turning off Internet Sharing for all networks. – Hopeless Oct 19 '19 at 01:01
  • I couldn't delete any of the extra adapters that were on my computer, so I disabled all but the one I knew I wanted. Then things started working again. Thanks! – Alex Dresko Sep 16 '20 at 20:35
  • I had the same problem when using shared internet, but still do not understand actually what is the reason for this behaviour... – Jakub Krampl May 03 '21 at 12:51
  • 1
    Thanks! Solved my problem too. I was sharing my internet per WiFi hotspot – Gledi May 11 '21 at 14:18
  • 1
    netstat shows the ports being used by a process. Ports can also be excluded from usage. You can see them via `netsh interface ipv4 show excludedportrange protocol=tcp` – Daniel Rose Jul 06 '21 at 15:47
  • @DanielRose, thanks. I found out, that the port I was using was within the excluded range. I changed it to another one outside of the range and everything works fine now. I think, your comment deserves to be a separate answer – dodbrian Sep 13 '21 at 16:19
  • Thanks resolved it was cause of VMware ethernet – zakiblacki Feb 20 '23 at 14:58
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"

Towhidul Islam Tuhin
  • 1,051
  • 13
  • 10
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

Daniel Rose
  • 17,233
  • 9
  • 65
  • 88
  • 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) – Homayoun Behzadian Jun 10 '22 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. – Marc Levesque Jul 28 '22 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 – Tejas Patel Apr 11 '23 at 06:53
  • @TejasPatel you may restart WinNAT service to release reserved ports – Homayoun Behzadian Apr 11 '23 at 13:23
  • The solution from @Parsa with restarting "Host Network Service" removed the port from the excluded port range. – Jonas Marty Aug 02 '23 at 08: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.

Gareth
  • 439
  • 5
  • 12
  • 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 03 '20 at 03: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.

Sunny
  • 2,183
  • 1
  • 17
  • 13
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.

Rwt
  • 51
  • 1
  • 1
5

Run the terminal as an administrator then run this :

net stop hns
net start hns
mostafa kazemi
  • 514
  • 6
  • 7
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

David Klempfner
  • 8,700
  • 20
  • 73
  • 153
Finitely Failed
  • 119
  • 3
  • 14
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.

AJM
  • 41
  • 2
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.

stimms
  • 42,945
  • 30
  • 96
  • 149
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.

Gian
  • 31
  • 4
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.

Rob
  • 3,488
  • 3
  • 32
  • 27
  • 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 '23 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.

Ian
  • 1,221
  • 1
  • 18
  • 30
1

Running iisreset in a command window fixed it for me.

MFry
  • 81
  • 1
  • 3
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.

wip
  • 2,313
  • 5
  • 31
  • 47
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.

Andrew H
  • 11
  • 3
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.

terabyte
  • 11
  • 2
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!

Eric Mutta
  • 1,144
  • 1
  • 11
  • 15
0

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

zakiblacki
  • 187
  • 1
  • 10
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

XouDo
  • 945
  • 10
  • 19
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

Serj Sagan
  • 28,927
  • 17
  • 154
  • 183
-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

kixuan
  • 1