An attempt was made to access a socket in a way forbidden by its access permissions. Why? [duplicate]
Asked Answered
K

25

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

Kindliness answered 5/5, 2012 at 11:11 Comment(7)
If the exception is happening at the CREATE, the I expect you need to be running as Administrator to create RAW sockets.Violaviolable
Highly related, if not duplicate of An attempt was made to access a socket in a way forbidden by its access permissionsSubotica
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:25Oden
try to test by another port that smaller than 10000Obligor
This happened to me when trying to run manually an exe which is a netcore API. It was IIS that holded the port open.Sisyphus
It just means the port is in use. Either kill whatever is holding the port open, or pick another port.Akbar
your service port could also be in the windows excluded ports range. you can check it using netsh interface ipv4 show excludedportrange protocol=tcp. if it is, just pick another port and set it in launchSettings.jsonSacculate
S
152

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

Subroutine answered 5/5, 2012 at 12:46 Comment(10)
Sysinternals TCPView can be helpful as well for checking if used by another process (as I just ran into)Bell
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.Violaviolable
I've only ever seen this error at bind. Here's an example: help.octopusdeploy.com/discussions/problems/…Subroutine
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.Belch
Are you running a firewall or iptables rules that block the port? Also, what user is your app running as?Subroutine
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 # 80Zola
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.Varini
It might also be in an excluded range, check with netsh interface ipv4 show excludedportrange protocol=tcpBreve
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.Verdugo
For me, I forgot that I recently installed another application that exposed services on the port I was trying to use.Botello
M
770

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

Mcwilliams answered 7/5, 2021 at 22:13 Comment(5)
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?Excurrent
If you have "System error 5 has occurred." when typing these commands, just open your terminal as an administrator (source: lifewire.com/…)Defective
Worked on my long-standing socket ::bind problem. Anybody know how to start and stop the hns programmatically?Contrasty
"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.Contrasty
I don't have this service on Windows 11. Is it specific to Windows 10 and earlier?Donaugh
S
152

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

Subroutine answered 5/5, 2012 at 12:46 Comment(10)
Sysinternals TCPView can be helpful as well for checking if used by another process (as I just ran into)Bell
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.Violaviolable
I've only ever seen this error at bind. Here's an example: help.octopusdeploy.com/discussions/problems/…Subroutine
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.Belch
Are you running a firewall or iptables rules that block the port? Also, what user is your app running as?Subroutine
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 # 80Zola
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.Varini
It might also be in an excluded range, check with netsh interface ipv4 show excludedportrange protocol=tcpBreve
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.Verdugo
For me, I forgot that I recently installed another application that exposed services on the port I was trying to use.Botello
A
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!

Anatropous answered 3/3, 2015 at 17:31 Comment(6)
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.Violaviolable
@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.Imtiaz
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 scenariosSubotica
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.Gunilla
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!Adherent
I just shut down visual studio and then reopened it and it worked!Cultured
B
36

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.

Belch answered 22/11, 2015 at 19:41 Comment(8)
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.Joppa
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?Bunion
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?Esque
@Esque 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.Belch
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!Behn
I had the same problem when using shared internet, but still do not understand actually what is the reason for this behaviour...Floorman
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=tcpOt
@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 answerRrhoea
A
31

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"

Anesthesia answered 15/11, 2020 at 6:42 Comment(0)
O
14

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

Ot answered 14/9, 2021 at 7:3 Comment(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)Grower
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.Hosfmann
@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 nowFiduciary
@TejasPatel you may restart WinNAT service to release reserved portsGrower
The solution from @Mcwilliams with restarting "Host Network Service" removed the port from the excluded port range.Herat
D
10

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.

Dusen answered 27/12, 2016 at 6:36 Comment(1)
In my case, I was using tinywall that blocked app.Andromeda
B
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.

Banket answered 10/9, 2018 at 10:50 Comment(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.Stanchion
O
10

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.

Ommiad answered 24/5, 2023 at 23:21 Comment(1)
this one fixed the error for me, i changed the port and worked.Flanders
L
7

Run the terminal as an administrator then run this :

net stop hns
net start hns
Leonardaleonardi answered 8/2, 2023 at 15:59 Comment(0)
E
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.

Extrovert answered 9/5, 2017 at 15:29 Comment(0)
P
5

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

Piccaninny answered 29/5, 2020 at 7:36 Comment(1)
Thanks. This is explained here: learn.microsoft.com/en-us/windows/uwp/networking/socketsLeveller
A
5

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.

Afternoon answered 29/12, 2022 at 8:3 Comment(0)
S
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.

Slurry answered 11/10, 2019 at 18:57 Comment(0)
I
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.

Iseabal answered 1/10, 2022 at 22:30 Comment(0)
D
2

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.

Derringer answered 10/5, 2019 at 2:34 Comment(0)
S
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.

Spendable answered 16/8, 2022 at 13:5 Comment(0)
L
1

Running iisreset in a command window fixed it for me.

Leonteen answered 15/10, 2018 at 14:35 Comment(0)
J
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.

Jenijenica answered 15/10, 2021 at 20:6 Comment(0)
E
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.

Eden answered 26/6, 2023 at 13:1 Comment(0)
E
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

Entomo answered 31/5, 2023 at 13:30 Comment(0)
F
0

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

Functionalism answered 18/8, 2023 at 3:6 Comment(0)
S
-1

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!

Sinotibetan answered 10/12, 2022 at 2:24 Comment(0)
M
-1

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

Macneil answered 20/2, 2023 at 15:1 Comment(0)
M
-1

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

Marxist answered 1/5, 2023 at 12:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.