Search code examples
c#tcpclientnetworkstream

C# TCPClient SocketError 10051 during read operation. Adapters IP is empty


I have an application which uses the TCPClient to connect to a TCPServer and exchange data every 300ms. The application and connections works as expected. I tested the connection for 2 days and is runs all the time without any errors. Today I got an error which I can not solve and which I do not understand. The computer(TCPClient) and the TCPServer are in the same network and both get their IP adresses via DHCP. The application starts with reading the network adapter information and reads the network adapters ip adress and other information:

NetworkInterface[] adapter = NetworkInterface.GetAllNetworkInterfaces();

Two adapters are found on the computer, the following code delivers the IP adresses:

foreach (UnicastIPAddressInformation ip in adapter.GetIPProperties().UnicastAddresses)
{
   if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
   {
      this.ip = ip.Address.ToString();
      this.mask = ip.IPv4Mask.ToString();
   }
}

Adapter one: IP: 192.168.0.153, Mask: 255.255.255.0 Adapter two: IP: 127.0.0.1, Mask: 255.0.0.0 (Name Loopback Pseudo-Interface1)

I know the ip adress of my server and start to connect.

controller = new TcpClient();
controller.Connect(192.168.0.0, 5001);
.... //Continues when controller.Connected == true
static NetworkStream ns_controller = controller.GetStream();
ns_controller.WriteTimeout = 100;
ns_controller.ReadTimeout = 10;

After that my application did write and read to and from the network stream data for 800 seconds. Then a new read instructions ends in the catch block:

try
{
   byte[] r = new byte[100];
   int anz = 0;
   anz = ns_controller.Read(r, 0, r.Length);
}
catch (Exception ex)
{
   //Output of the inner exception data and reset of communication
}

InnerException.ErrorCode: 10051 and InnerException.Message: A socket operation referred to an unavailable network

When I reset the communication because of the error the network adapters are read 100ms after the exception again with the same code as in the beginning. The only difference is that the ip adress and network mask are now "" empty. After that I closed my application and tried it again. The ip adress of the network interface was 192.168.0.153 again and did not change.

I want to ask if anyone else had that problem before and what is the reason for the problem? I only found some questions about the errorcode 10051 occuring while connecting to a server. Why can the ip adress of the controller be empty for a short time and then be again the same value as before?

I know that I cannot provide all information but I hope that this is enough. The problem is that the provided information are all I have recorded in my protocol. I was not able to force the error again another time to record the complete informations. Any help or hint is welcome.


Solution

  • I have faced not exactly the same problem but similar to this and I resolved it by reaching to the root cause. You may try following it might help you out or at least it may give you some clues to resolve your issue:

    Add one more catch block by using ScoketExeption with all possible socket errors

      try
        {
                //Your code .................
                Socket socket = controller.Client; // not necessary to use but could be helpful to gracefully close the socket and for retry connection in catch( ) e.g. if(socket!=null) socket.close();  
                // your code..................
    
            }
            catch(SocketException se)
            {
            string exception = string.Empty;
            switch (se.SocketErrorCode)
            {
                case SocketError.Success:
                    exception = "Success";
                    break;
                case SocketError.SocketError:
                    exception = "Socket Error";
                    break;
                case SocketError.Interrupted:
                    exception = "Socket Interrupted";
                    break;
                case SocketError.AccessDenied:
                    exception = "Access Denied";
                    break;
                case SocketError.Fault:
                    exception = "Socket Falut";
                    break;
                case SocketError.InvalidArgument:
                    exception = "Invalid Argument";
                    break;
                case SocketError.TooManyOpenSockets:
                    exception = "Too Many Open Sockets";
                    break;
                case SocketError.WouldBlock:
                    exception = "Socket Blocked";
                    break;
                case SocketError.InProgress:
                    exception = "In progress";
                    break;
                case SocketError.AlreadyInProgress:
                    exception = "Already in progress";
                    break;
                case SocketError.NotSocket:
                    exception = "Not Socket";
                    break;
                case SocketError.DestinationAddressRequired:
                    exception = "Destination Address Required";
                    break;
                case SocketError.MessageSize:
                    exception = "Message Size Error";
                    break;
                case SocketError.ProtocolType:
                    exception = "Protocol Type Error";
                    break;
                case SocketError.ProtocolOption:
                    exception = "Protocol Option Error";
                    break;
                case SocketError.ProtocolNotSupported:
                    exception = "Protocol Not Supported";
                    break;
                case SocketError.SocketNotSupported:
                    exception = "Socket Not Supported";
                    break;
                case SocketError.OperationNotSupported:
                    exception = "Operation Not Supported";
                    break;
                case SocketError.ProtocolFamilyNotSupported:
                    exception = "Protocol Family Not Supported";
                    break;
                case SocketError.AddressFamilyNotSupported:
                    exception = "Address Family Not Supported";
                    break;
                case SocketError.AddressAlreadyInUse:
                    exception = "Adreess Already In Use";
                    break;
                case SocketError.AddressNotAvailable:
                    exception = "Address Not Avaialble";
                    break;
                case SocketError.NetworkDown:
                    exception = "Network Down";
                    break;
                case SocketError.NetworkUnreachable:
                    exception = "Network Unreachable";
                    break;
                case SocketError.NetworkReset:
                    exception = "Network Reset";
                    break;
                case SocketError.ConnectionAborted:
                    exception = "Connection Aborted";
                    break;
                case SocketError.ConnectionReset:
                    exception = "Connection Reset";
                    break;
                case SocketError.NoBufferSpaceAvailable:
                    exception = "No Buffer Space Available";
                    break;
                case SocketError.IsConnected:
                    exception = "Connected";
                    break;
                case SocketError.NotConnected:
                    exception = "Not Connected";
                    break;
                case SocketError.Shutdown:
                    exception = "Shutdown";
                    break;
                case SocketError.TimedOut:
                    exception = "Timed Out";
                    break;
                case SocketError.ConnectionRefused:
                    exception = "Connection Refused";
                    break;
                case SocketError.HostDown:
                    exception = "Host Down";
                    break;
                case SocketError.HostUnreachable:
                    exception = "Host Unreachable";
                    break;
                case SocketError.ProcessLimit:
                    exception = "Process Limit";
                    break;
                case SocketError.SystemNotReady:
                    exception = "System Not Ready";
                    break;
                case SocketError.VersionNotSupported:
                    exception = "Version Not Supported";
                    break;
                case SocketError.NotInitialized:
                    exception = "Not Initialized";
                    break;
                case SocketError.Disconnecting:
                    exception = "Disconnecting";
                    break;
                case SocketError.TypeNotFound:
                    exception = "Type Not Found";
                    break;
                case SocketError.HostNotFound:
                    exception = "Host Not Found";
                    break;
                case SocketError.TryAgain:
                    exception = "Try Again";
                    break;
                case SocketError.NoRecovery:
                    exception = "No Recovery";
                    break;
                case SocketError.NoData:
                    exception = "No Data";
                    break;
                case SocketError.IOPending:
                    exception = "IO Pending";
                    break;
                case SocketError.OperationAborted:
                    exception = "Operation Aborted";
                    break;
                default:
                    exception = "Un Specified Error";
                    break;
            }
        }