"System.Net.Sockets.SocketException (0x80004005): An attempt was made to access a socket in a way forbidden by its access permissions"
OK I know this problem has occurred many times before on S.O., but I cannot find a solution. Here is my question: what are possible causes of this.
Points:
Happens irrespective of firewall
Ports are open
Destination is open and connections have been working in the past
Since working connections, no changes to firewalls or virus scanners, can rule those out.
Running as administrative user
Source port is 23876
Destination port is variable, depends on detected client from another source
Windows 8.1
One more point - this error also happened after porting to .NET Core.
The only change is that I am trying to share ports but I can't see the connection between that and the error.The code to connect is
client = new TcpClient();
client.Client.SetSocketOption(
SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
client.Client.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, 0);
client.Client.Bind(ipLocalEndPoint);
client.Client.Connect(ep);
where the local endpoint is reused.
What are the possible causes of this error? It is happening on every BIND call.
OK this all turned out to be me being incredibly stupid.
What I had done, and forgotten I had done, is establish a TcpListener on the same port, with this code _tcpListener.ExclusiveAddressUse = false; not working as I expected.
Related
I have a TCP socket based client server system.
Everything works fine but when network is disconnected form client end and reconnect it again i get automatically SocketError.ConnectionReset send form client and regarding this command the socket is closed in the server side. this is also fine.
but when i look in to the client side it shows the socket is still connected with server. (regarding socket is still connected with server [It does not happen every time], sometime it shows disconnected and some times shows connected)
Does it make sense that "server get a SocketError.ConnectionReset from
client end but client is still connected"?
So i want to know what is the possible reasons of SocketError.ConnectionReset and how to handle such type of problem i have mentioned?
Again i say, Everything is working fine in normal environment (e.g if i exit the client it is disconnected the socket same for the server)
Thanks in advance.
EDIT:
Here is the code in the client side. actually it's a timer that tick every 3 second through programs lifetime and check if Socket is connected or not if its disconnected then it tries to reconnect again through a new socket instance
private void timerSocket_Tick(object sender, EventArgs e)
{
try
{
if (sck == null || !sck.Connected)
{
ConnectToServer();
}
}
catch (Exception ex)
{
RPLog.WriteDebugLog("Exception occcured at: "+ System.Reflection.MethodBase.GetCurrentMethod().ToString()+"Message: "+ex.Message);
}
}
In normal situation (without network disconnect/reconnect) if TCP server get a
SocketError.ConnectionReset form any client, in the client side i see
clients socket is disconnected and it tries to reconnect it again
through the code shown. but when situation happen explained earlier,
server gets a SocketError.ConnectionReset but client shows it still
connected. though the TCP server shows the reset command is send form the exact client
side.
There are several causes but the most common is that you have written to a connection that has already been closed but he other end. In other words, an application protocol error. When it happens you have no choice but to close the socket, it is dead. However you can fix the underlying cause.
When discussing a TCP/IP issue like this, you must mention the network details between the client and the server.
When one side says the connection is reset, it simply means that on the wire a RST packet appears. But to know who sends the RST packet and why, you must utilize network packet captures (by using Wireshark and any other similar tools),
https://en.wikipedia.org/wiki/Transmission_Control_Protocol
You won't easily find out the cause at .NET Framework level.
The problem with using Socket.Connected as you are is that it only gives you the connected state as at the last Send or Receive operation. i.e. It will not tell you that the socket has disconnected unless you first try to send some data to it or receive data from it.
From MSDN description of the Socket.Connected property:
Gets a value that indicates whether a Socket is connected to a remote host as of the last Send or Receive operation.
So in your example, if the socket was functioning correctly when you last sent or received any data from it, the timerSocket_Tick() method would never call ConnectToServer(), even if the socket was now not connected.
how to handle such type of problem i have mentioned?
Close the socket and initiate a new connection.
These errors are getting more and more frequent on my Game Server. They are causing the server to keep closing and restarting...
System.Net.Sockets.SocketException (0x80004005): An established connection was aborted by the software in your host machine
at System.Net.Sockets.Socket.BeginSend(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags, AsyncCallback callback, Object state)
at iRP.Game.Sessions.Session.SendData(Byte[] Data)
This is the code from which these errors are generated:
public void SendData(byte[] Data)
{
try
{
if (mSocket == null)
{
//Output.WriteLine("[SND] Socket has a null exception, which means it is now invalid. Remove this socket!", OutputLevel.CriticalError);
}
else
{
mSocket.BeginSend(Data, 0, Data.Length, SocketFlags.None, sendCallback, mSocket);
}
}
catch (Exception e)
{
string WhatToWrite = "Error handled (SESSION): " + e.ToString() + "\n\n" + e.Message + "\n\nStack: " + e.StackTrace + Environment.NewLine + "\n\n";
File.AppendAllText(Environment.CurrentDirectory + "\\data\\fatal.txt", WhatToWrite);
Program.Stop();
}
}
The buffer sizes are correctly set, we are using KeepAlive on the socket and were using Send and Receive Timeouts.
People suggested that disabling the firewall would help, but whenever I do this our Game Server (Dedicated Server) restarts itself as if it's under attack, so the firewall must remain enabled.
Anyone else got any other solutions for this?
PS: We are behind DDoS Mitigation Services which may be limiting the number of connections...
An established connection was aborted by the software in your host machine
That is a boiler-plate error message, it comes out of Windows. The underlying error code is WSAECONNABORTED. Which really doesn't mean more than "connection was aborted". You have to be a bit careful about the "your host machine" part of the phrase. In the vast majority of Windows application programs, it is indeed the host that the desktop app is connected to that aborted the connection. Usually a server somewhere else.
The roles are reversed however when you implement your own server. Now you need to read the error message as "aborted by the application at the other end of the wire". Which is of course not uncommon when you implement a server, client programs that use your server are not unlikely to abort a connection for whatever reason. It can mean that a fire-wall or a proxy terminated the connection but that's not very likely since they typically would not allow the connection to be established in the first place.
You don't really know why a connection was aborted unless you have insight what is going on at the other end of the wire. That's of course hard to come by. If your server is reachable through the Internet then don't discount the possibility that you are being probed by a port scanner. Or your customers, looking for a game cheat.
This problem appear if two software use same port for connecting to the server
try to close the port by cmd according to your operating system
then reboot your Android studio or your Eclipse or your Software.
Could be related to the maximum number of concurrent requests. I was able to fix it with two solutions:
Increase the default limit of the max concurrent connections (by default it is set to 2):
ServicePointManager.DefaultConnectionLimit = 25
Wrap sending requests around a buffer: could use ConcurrentQueue to limit the rate, or implement a simple wait as the following:
while (activeRequests >= maxConcurrentRequests)
Thread.Sleep(1000);
Interlocked.Increment(ref activeRequests);
var response = await _client.GetStreamAsync(endpoint);
Interlocked.Decrement(ref activeRequests);
While the answer from Hans is an excellent high level summary of the error that worked great for getting me started, I ended up finding a page that explained the root cause well enough that I was able to recreate it with a python script.
The page presents a couple different descriptions of this error that are more detailed than the "connection was aborted" paraphrasing from Hans's answer but still pretty cryptic and not very informative.
The post then explains this scenario that would produce the error:
An HTTP POST is to be sent to an HTTP server.
The server begins reading the POST and notices that the HTTP request header is invalid.
It immediately sends an HTTP response (with an error status, perhaps status=400) and closes the connection without trying to continue reading the remainder of the HTTP request that is forthcoming.
Meanwhile, the client is still happily writing the remainder of the HTTP request to the socket. (Remember a TCP/IP socket connection needs to be closed from both sides. In this case, the server has closed its side, but the client is still pumping data into the half-open connection.)
The client finishes writing the HTTP POST to the socket — meaning that data has been buffered to Winsock. The client application then tries to read the HTTP response, but it cannot because the outgoing retransmission (of the buffered data by WinSock) failed and the socket connection was shutdown on the client side (by Winsock). Even though the HTTP server sent the response, it is lost and cannot be retrieved. The error your application will receive when trying to read the HTTP response on the socket is WSAECONNABORTED
Wikipedia also has a page to explain what winsock is, but all you really need to know for this scenario is that its the Windows socket API.
I had "ManageEngine Agent" installed on my computer, which was blocking my connection to the databases, so uninstalling it was the solution.
Check which application could block the connection to your DB.
I know this question has been asked many times. I've read ALL the answers and tried EVRY piece of code I could find. After a few days I'm so desperate that I have to ask you for help.
I have a device and a PC in my home network. The device sends UDP broadcast messages. On my PC I can see those messages in wireshark:
Source Destination Length
192.168.1.102 0.0.0.0 UDP 60 Source port: 9050 Destination port: 0
That means the packets are arriving on my PC. My next step was to create a C# application that receives those packets. As mentioned above I tried every possible solution, but it just won't receive anything.
So I guess there must be something very basic I'm doing wrong.
Can anyone help me out? Thanks!
Just experienced the same issue, and wanted to share what fixed it for me.
Briefly: it seems that Windows Firewall was somehow the cause of this weird behavior, and just disabling the service does not help. You have to explicitly allow incoming UDP packets for specific program (executable) in Windows Firewall inbound rules list.
For full case description, read on.
My network setup is: IP of my (receiving) machine was 192.168.1.2, IP of sending machine was 192.168.1.50, and subnet mask on both machines was 255.255.255.0.
My machine is running Windows 7 x64.
This is the code (roughly) that I used:
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 0);
sock.Bind(iep);
sock.EnableBroadcast = true;
EndPoint ep = (EndPoint)iep;
byte[] buffer = new byte[1000];
sock.ReceiveFrom(buffer, ref ep);
Initially this did not work unless I sent a broadcast packet from that socket before I call ReceiveFrom on it. I.e. adding this line before ReceiveFrom call:
sock.SendTo(someData, new IPEndPoint(IPAddress.Broadcast, somePort))
When I didn't send the broadcast packet first from receiving socket, incoming broadcast packets were not received by it, even though they appeared in Wireshark (destination of packets was 255.255.255.255).
I thought that it looks like firewall is messing with incoming packets (unless some kind of UDP hole is opened first by outgoing packet - even though I haven't heard before that UDP hole punching applies to broadcast packets somehow), so I went to services and disabled Windows firewall service altogether. This changed nothing.
However, after trying everything else, I re-enabled the firewall service, and tried to run the program again. This time, firewall prompt appeared asking me whether I want to allow MyProgram.vshost.exe process (I was debugging in Visual Studio) through firewall, I accepted it, and voila - everything worked! Incoming packets were being received now!
You are OK, they have something wired in the code which causes the problem. (I haven't read the article, just copy pasted)
It always works from the local machine, but from a remote machine it will fail for some reason.
To fix this:
In the Broadcst.cs they broadcast twice. once for the localhost and then for the target IP adress (iep2). simply remove the
sock.SendTo(data, iep1);
and it should work.
No idea why.
Just to be clear, all of the TCPClients I'm referring to here are not instances of my own class, they are all instances of System.Net.Sockets.TcpClient from Mono's implementation of .NET 4.0.
I have a server that is listening for client connections, as servers do. Whenever it gets a new client it creates a new TCPClient to handle the connection on a new thread. I'm keeping track of all the connections and threads with a dictionary. If the client disconnects, it sends a disconnect message to the server, the TCPClient is closed, the dictionary entry is removed and the thread dies a natural death. No fuss, no muss. The server can handle multiple clients with no problem.
However, I'm simulating what happens if the client gets disconnected, doesn't have a chance to send a disconnect message, then reconnects. I'm detecting whether a client has reconnected with a username system (it'll be more secure when I'm done testing). If I just make a new TCPClient and leave the old one running, the system works just fine, but then I have a bunch of useless threads lying around taking up space and doing nothing. Slackers.
So I try to close the TCPClient associated with the old connection. When I do that, the new TCPClient also dies and the client program throws this error:
E/mono (12944): Unhandled Exception: System.IO.IOException: Write failure ---> System.Net.Sockets.SocketException: The socket has been shut down
And the server throws this error:
Unable to write data to the transport connection: An established connection was aborted by the software in your host machine.
Cannot read from a closed TextReader.
So closing the old TCPClient with a remote endpoint of say: 192.168.1.10:50001
Also breaks the new TCPClient with a remote endpoint of say:192.168.1.10:50002
So the two TCPClient objects have the same remote endpoint IP address, but different remote endpoint ports. But closing the one seems to stop the other from working. I want to be able to close the old TCPClient to do my cleanup, without closing the new TCPClient.
I suspect this is something to do with how TCPClient works with sockets at a low level, but not having any real understanding of that, I'm not in a position to fix it.
I had a similar issue on my socket server. I used a simple List instead of a dictionary to hold all of my current connections. In a continuous while loop that listens for new streams, I have a try / catch and in the catch block it kills the client if it has disconnected.
Something like this on the sever.cs:
public static void CloseClient(SocketClient whichClient)
{
ClientList.Remove(whichClient);
whichClient.Client.Close();
// dispose of the client object
whichClient.Dispose();
whichClient = null;
}
and then a simple dispose method on the client:
public void Dispose()
{
System.GC.SuppressFinalize(this);
}
EDIT: this paste is the OPs resolution which he or she found on their own with help from my code.
So to clarify, the situation is that I have two TCPClient objects TCPClientA and TCPClientB with different remote endpoints ports, but the same IP:
TCPClientA.Client.RemoteEndPoint.ToString();
returns: 192.168.1.10:50001
TCPClientB.Client.RemoteEndPoint.ToString();
returns: 192.168.1.10:50002
TCPClientA needs to be cleaned up because it's no longer useful, so I call
TCPClientA.Close();
But this closes the socket for the client at the other end of TCPClientB, for some reason. However, writing
TCPClientA.Client.Close();
TCPClientA.Close();
Successfully closes TCPClientA without interfering with TCPClientB. So I've fixed the problem, but I don't understand why it works that way.
Looks like you have found a solution but just so you are aware there are many similar pitfalls when writing client/server applications in .net. There is an open source network library (which is fully supported in mono) where these problems have already been solved, networkComms.net. A basic sample is here.
Disclaimer: This is a commercial product and I am the founder.
This is clearly an error in your code. Merely closing one inbound connection cannot possibly close another one. Clearly something else is happening elsewhere in your code.
I run my application on a network and in some cases the client lost connection to the server. After this time, when I wanted to send a message to the server I receive the following error: Operation not allowed on non-connected sockets (something like this).
I thought to create an event for object type TcpClient and when tcp_obj.Connected = false to call a function to discontinue execution of the current code. How could I do this?
Or giving me other suggestios.
Thanks.
I know at least from socket programming in Java that when a client loses connection to the server, the server does not and can not know about it. You need a heartbeat of some sort to detect the early disconnection.
We often use a heartbeat in our client/server applications to detect early disconnections and log them on the server. This way the server can close the associated socket and release the connection back to the pool.
Simply send a command to the client periodically and wait for a response. If no response is garnered within a timeout assume disconnect and close streams.
I would simply first check your connection object to ensure you are connected, prior to attempting to send the message. Also make sure that you are putting your send-logic inside of a try-catch, so that if you do happen to get disconnected mid transmission, you'll be able to resume without blowing your application apart.
Psuedo-Code:
private void SendMessage(string message, Socket socket)
{
if(socket.connectionState = States.Connected)
{
try{
// Attempt to Send
}
catch(SocketException Ex)
{
// Disconenct, Additional Cleanup Etc.
}
}
}
If you are in C#, prior to your connection state changing, you will have a socket disconnected event fire, prior to your connection state changing. Make sure you tie this event up as soon as your socket connects.
Can we know why you use TCP sockets? Is for calling a tcp device o server code?
I recommend you if is for calling a .net server app use Windows Communication Foudation. It is simple to expose services by net.tcp, http, etc.
Regards,
Actually this is a very old problem,
If I understand your question correctly you need a way to know whether you're application is still connected to the server or vice versa.
If so then a workaround is to have a UDP connection just to check the connectivity (overhead I know, but its much better then polling on Connected state), you could check just before you send you're data.
Since UDP is not Connection oriented you don't need to be connected when you send the data