129
 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 don't understand why...it worked and now it doesn't. could someone help me? i am streaming with vlc, and i wan't to receive the packets, do some reports, and then restream local to a player

moffeltje
  • 4,264
  • 4
  • 29
  • 52
andrew
  • 1,557
  • 3
  • 13
  • 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
  • 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
  • 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

14 Answers14

214

I restarted this service : Host Network Service on windows Services program. And it worked.

You can run these commands in the windows terminal instead, as @admin mentioned in comment section:

net stop hns
net start hns
Parsa
  • 3,306
  • 1
  • 22
  • 32
113

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

stark
  • 11,447
  • 3
  • 32
  • 46
  • 2
    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
  • 7
    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
  • 30
    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
  • 8
    It might also be in an excluded range, check with `netsh interface ipv4 show excludedportrange protocol=tcp` – nexus Feb 07 '21 at 05:10
58

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
  • 599
  • 4
  • 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
  • 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
32

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,123
  • 4
  • 33
  • 59
  • 1
    thanks, the internet sharing setting ended up being my problem – kellpossible Dec 12 '17 at 03:36
  • 3
    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
  • 2
    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
15

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"

9

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
  • 389
  • 4
  • 10
  • 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
8

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
  • 1,516
  • 1
  • 13
  • 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
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
  • 41,342
  • 28
  • 92
  • 147
3

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
  • 7,367
  • 16
  • 55
  • 115
Finitely Failed
  • 109
  • 3
  • 14
2

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
  • 16,753
  • 9
  • 65
  • 86
1

Running iisreset in a command window fixed it for me.

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

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,205
  • 3
  • 30
  • 46