Client connect failed error code 10038

Is there any solution for 10038 server error .i have done coding in c++; the server runs fine 10 to 12 hours but sudenly it gives 10038 socket error

Is there any solution for 10038 server error .i have done coding in c++;
the server runs fine 10 to 12 hours but sudenly it gives 10038 socket error

asked Oct 16, 2010 at 8:32

SunilRai86's user avatar

SunilRai86SunilRai86

9706 gold badges16 silver badges26 bronze badges

0

Without seeing your code: the symptom you describe sounds like you are leaking memory/resources, i.e. you are forgetting to free/delete objects you are allocating. It could also be a timing issue. I suggest you post your (cut-down) code.

10038 (WSAENOTSOCK): Socket operation on nonsocket. An operation
was attempted on something that is not
a socket. Either the socket handle
parameter did not reference a valid
socket, or for select, a member of an
fd_set was not valid.

answered Oct 16, 2010 at 8:34

Mitch Wheat's user avatar

Mitch WheatMitch Wheat

293k43 gold badges463 silver badges538 bronze badges

2

I bet you are accessing a socket that you already closed. This is a very common timing bug in WinSock programming — the good news (and bad news, because it’s hard to reproduce) is that you are not hitting it very often so it’s likely your code does not need much work to make it perfect. I think you should add thread-safe diagnostics that output a string including the socket value (an int, basically) on every open and close, and from anywhere you see this 10038 or other unexpected errors.

If you can add those diagnostics and then set up a stress test that focuses on open and close areas in your program (you may need to strip down the code to a small subset for unit testing of the sockets handling, maybe doing this back-to-back on localhost, or to two LAN-connected machines) then it will likely manifest much more quickly than 10-12 hours and you may find and fix other timing windows along the way. The goal is to try to compress 10-12 hours of ‘normal’ socket activity into as small a space of time as possible, to really expose any hard-to-detect concurrency problems.

answered Oct 16, 2010 at 12:23

Steve Townsend's user avatar

Steve TownsendSteve Townsend

53.2k9 gold badges91 silver badges139 bronze badges

There may be two reasons for this:

  1. Your socket descriptor in uninitialized (i.e. doesn’t reference a valid socket).
  2. You closed this socket (by a call to closesocket), and still try to use it.

Such an error is always a bug, it’s not related to the real network activity/state and etc. This is equivalent (in some sense) to either trying to use a resource/memory after you free it, or simply referencing an uninitialized pointer.

So that in order to solve the 10038 you must fix your code.

P.S. If you have a multi-threaded application — it’s likely that you close the socket in one thread, whereas the other thread still trying to use it.

Anyway, there’s a good practice to initialize socket descriptors to INVALID_SOCKET at the beginning. Also set it to INVALID_SOCKET immediately after you close it.

Then, before trying to use it you may check if the socket is valid. In such a way you may find the problematic scenario.

answered Oct 16, 2010 at 10:21

valdo's user avatar

valdovaldo

12.5k2 gold badges35 silver badges65 bronze badges

Also look out for the fact that — at least in Windows — you will get 10038 if you try to send on a socket on one thread that was opened in a different thread.

answered Nov 9, 2017 at 18:17

Ted W's user avatar

Ted WTed W

2394 silver badges11 bronze badges

1

>
CSocket::Connect — ошибка 10038
, как лечить?

  • Подписаться на тему
  • Сообщить другу
  • Скачать/распечатать тему



Сообщ.
#1

,
18.05.06, 08:00

    писал клиент-сервер. дома на тестовой машине пахало на ура.
    была сеть из двух машин с IP 192.168.0.1 и 192.168.0.2
    принес проект на работу и вот такая хрень. 10038 ошибка. кек лечить не пойму.
    а на работе все машины с внешними IP.
    клиент:

    ExpandedWrap disabled

       char ip_address[256];

       sprintf(ip_address, «%d.%d.%d.%d», adr[0], adr[1], adr[2], adr[3]);

       int port = 2106;

       BOOL res = pConnect->Connect(ip_address, port);

    server:

    ExpandedWrap disabled

      for(;;)

       {

         fd_set readset;

         FD_ZERO( &readset );

         FD_SET( login_socket, &readset );

         FD_SET( game_socket, &readset );

         for( int it = 0; it < clients.GetSize(); it++)

          FD_SET( clients.GetAt(it)->GetSocket(), &readset );

         timeval timeout;

         timeout.tv_sec = 0;

         timeout.tv_usec = 1;

         int mx = getmax( max( login_socket, game_socket ) );

         if( FD_ISSET( login_socket, &readset ) )

         {

           //this is new connect

            // sockaddr_in login_name;

           int client_sock = accept( login_socket, 0, 0 );

           if( client_sock < 0 )

           {

              printfex(RED, «error: accept() n»);

              exit();

              closesocket( login_socket );

              closesocket( game_socket );

              return 1;

           }

      //     fcntl( client_sock, F_SETFL, O_NONBLOCK );

           CClient* pClient = new CClient;

           pClient->SetSocket( client_sock );

           pClient->port = 2106;

           clients.add( pClient );

           if( -1 == m_Login->OnConnect(pClient) )

           {

             printfex(RED, «[L2 Serever] fatal connect to 2106n»);

             remove( pClient );

           }

           else printfex(YELLOW, «[L2 Serever] connect to 2106n»);

         }  

       }

    Добавлено 18.05.06, 08:07
    ЗЫ, пытался отрубить тачку от сети и поставить на ней «домашние» IP — один хрен не пашет.

    Добавлено 18.05.06, 08:52
    млин,

    ExpandedWrap disabled

       WSADATA WSAData ;

       if (WSAStartup (MAKEWORD(1,1), &WSAData) != 0)

       {

              //      ::MessageBox (NULL, TEXT(«WSAStartup failed!»), TEXT(«Error»), MB_OK);

              return;

       }

      char ip_address[256];

       sprintf(ip_address, «%d.%d.%d.%d», adr[0], adr[1], adr[2], adr[3]);

       int port = 2106;

       BOOL res = pConnect->Connect(ip_address, port);

    однако

    ExpandedWrap disabled

      WSADATA WSAData ;

       if (WSAStartup (MAKEWORD(1,1), &WSAData) != 0)

       {

              //      ::MessageBox (NULL, TEXT(«WSAStartup failed!»), TEXT(«Error»), MB_OK);

              return;

       }

    вызывалось при старте программы. чудеса однако.

    Сообщение отредактировано: progman — 18.05.06, 08:52


    Oleg2004



    Сообщ.
    #2

    ,
    18.05.06, 16:42

      progman
      Так а где — после какой функции — эта ошибка вылазит???
      WSAENOTSOCK (10038) Socket operation on non-socket.
      Berkeley description: An operation was attempted on something that is not a socket. The specified socket parameter refers to a file, not a socket.
      WinSock description: Same as Berkeley. The socket input parameter is not a valid socket handle (either it never was valid, it’s a file handle (not a socket handle), or if it was a socket handle, it has been closed).
      Detailed description:
      select(): fails with WSAENOTSOCK if any socket in an fd_set is an invalid socket handle.
      Developer suggestions: Did you close a socket inadvertently in one part of an application without keeping another part notified? Use socket state in an application and/or handle this error gracefully as a non-fatal error.
      WinSock functions: Any function that takes a socket as an input parameter: accept(), bind(), closesocket(), connect(), getpeername(), getsockname(), getsockopt(), ioctl socket(), listen(), recv(), recvfrom(), select(), send(), sendto(), setsockopt(), shutdown(), FD_CONNECT
      Additional functions: WSAAsyncSelect() should be in the list of functions (some applications might not register for or handle the FD_CONNECT message).


      progman



      Сообщ.
      #3

      ,
      19.05.06, 10:23

        Oleg2004
        вылезала сразу после
        BOOL res = pConnect->Connect(ip_address, port);

        клиентский сокет не мог законнекится на серверный.
        в инициализации окна стоял WSAStartup , очевидно не хватило одного вызова :huh: .

        поставил WSAStartup перед коннектом и заработало.


        Oleg2004



        Сообщ.
        #4

        ,
        19.05.06, 12:48

          progman

          Цитата

          поставил WSAStartup перед коннектом и заработало.

          Это виндовский закон — в любой сетевой программе надо инициализировать Winsock и затем в конце освободить все сетевые ресурсы — WSAСleanup

          0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)

          0 пользователей:

          • Предыдущая тема
          • C/C++: Сетевое программирование
          • Следующая тема

          [ Script execution time: 0,0263 ]   [ 16 queries used ]   [ Generated: 9.02.23, 09:01 GMT ]  

          Problem

          User authenticates to the Controller-on-Cloud «Citrix Storefront». User successfully sees the relevant Controller published application icon.

          User clicks on the Controller icon. There is a delay of approximately 1 minute. After this delay, and error appears.

          Symptom

          image 2915

          Citrix Receiver

          Unable to connect to the server. Contact your system administrator with the following error: Socket operation on non-socket (Socket Error 10038)

          Cause

          End user’s client device is using an old version of Citrix client.

          Example: 

          In one real-life example, the ‘bad’ end user had Citrix Receiver v4.12.0.18020 installed:

          image 2920

          Resolving The Problem

          Upgrade to the latest version of the Citrix client.

          Example:

          In one real-life example, upgrading from Citrix Receiver v4.12 to Citrix Workspace app version 2002 (released March 24th 2020)  solved the problem.

          Steps:

          Instructions on how to upgrade to the latest Citrix client are inside separate IBM Technote #6189477.

          Related Information

          Document Location

          Worldwide

          [{«Business Unit»:{«code»:»BU059″,»label»:»IBM Software w/o TPS»},»Product»:{«code»:»SSMRTZ»,»label»:»IBM Cognos Controller on Cloud»},»ARM Category»:[],»Platform»:[{«code»:»PF033″,»label»:»Windows»}],»Version»:»All Versions»,»Edition»:»»,»Line of Business»:{«code»:»LOB10″,»label»:»Data and AI»}}]

          1. Create an Application With the Help of the socket Module Without Error in Python
          2. the OSError: [WinError 10038] An Operation Was Attempted on Something That Is Not a Socket

          OSError: [WinError 10038] an Operation Was Attempted on Something That Is Not a Socket

          With this explanation, we will learn what server and client are and how to use the socket module to create an application with the help of server and client. We will also learn how to avoid errors when making these types of applications in Python.

          Create an Application With the Help of the socket Module Without Error in Python

          Around the internet, the node can be a server or a client; of course, it can also be a client-to-client network where you have all the nodes and are talking to each other. It is a peer-to-peer network.

          We have servers on the internet listening to the clients, and they are waiting for the client to send a request.

          For example, when you go to google.com, the Google server, and you send a request to the Google server, the Google server will send you some response, i.e., a page or a Page Not Found message.

          Let’s start by creating two Python files, demo.py and client.py. We want to send the message from the server to the client.

          The server and client could be from different locations or outside the network.

          We will create the server, and then we will pass a message and see how this client receives the message from the server. To keep it simple, we are doing it on the localhost, but you can also do it on different systems.

          The first thing we need to do is to import the socket and create an instance. We will call the socket class and then specify the socket family.

          The socket family will be AF_INET, and the socket formula will be SOCK_STREAM.

          In the next step, we will need to bind the socket to the hostname on the port using the bind() method. Now, we have to listen for connections using the listen() method; the maximum number of connections would be 5.

          import socket
          
          SKT=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
          SKT.bind((socket.gethostname(),6060))
          SKT.listen(5)
          

          To find a connection with a client, we send a message from the server so that the client will receive the message.

          To do that, we will use the while loop that would be True. In this loop, we will create another socket that would be the client socket using the connect() method; it will be used in the client.py file.

          We are using the accept() method that returns two values; that is why we declared two variables that store the incoming socket and the address of the incoming connection. Now, we will print a message that shows a connection has been established from the specified address.

          while True:
              Client_Socket,Adress=SKT.accept()
              print(f'Connection has been established from {Adress}')
          

          Now we will need to send a message in bytes. The encoding will be utf-8, sent to each client connected with the socket.

          Client_Socket.send(bytes("Welcome to the server!!!","utf-8"))
          Client_Socket.close()
          

          Our socket is ready to listen for connection. Now we will work in the client.py file and use the same code except the connect() method.

          In the connect() method, we will use the same hostname, localhost, and port.

          Now, we are going to receive the message that is coming from the server. We will use the recv() method and pass it to 2048 bytes.

          We will print out this message to verify whether the message has been received or not.

          import socket
          
          SKT=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
          SKT.connect((socket.gethostname(),6060))
          
          MSG=SKT.recv(2048)
          
          print(f"Message has been received {MSG}")
          

          Now, the application is completed, so we will run the server first, the demo.py file; it is running, but nothing has happened. If we go to the client.py and run this file in an interactive window, we can see the response in the console when these files are running simultaneously.

          Application With the Socket Module Without Error - Output

          the OSError: [WinError 10038] An Operation Was Attempted on Something That Is Not a Socket

          There are some common reasons we get errors when creating this application. One reason might be that you forgot to run one file, both of them, or you are making a mistake anywhere.

          Let’s look at an example where the users often get this error.

          import socket
          
          SKT=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
          SKT.bind((socket.gethostname(),6060))
          SKT.listen(5)
          
          while True:
              Client_Socket,Adress=SKT.accept()
          
              while True:
          
                  print(f'Connection has been established from {Adress}')
                  Client_Socket.send(bytes("Welcome to the server!!!","utf-8"))
                  Client_Socket.close()
          

          Output:

          OSError: [WinError 10038] An operation was attempted on something that is not a socket
          

          This is because we are running a nested while loop, and both are True. When the outer while loop is executed, we accept the incoming connection from the client.

          The problem occurs when the inner while loop is executed.

          Since the inner while loop is True the first time, this loop executes perfectly, but in the second iteration, the while loop needs to accept an incoming connection. The accept() method calls from the outer loop, which will never be called; that is why it finds the socket no longer exists.

          Another reason the problem can occur is when you run these two files from the terminal. If you are working in VS code, run these two files individually in (current file in an interactive window).

          Application With the Socket Module - Run Current File in Interactive Window

          Complete demo.py File Code:

          import socket
          
          SKT=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
          SKT.bind((socket.gethostname(),6060))
          SKT.listen(5)
          
          while True:
              Client_Socket,Adress=SKT.accept()
              print(f'Connection has been established from {Adress}')
              Client_Socket.send(bytes("Welcome to the server!!!","utf-8"))
              Client_Socket.close()
          
          • Remove From My Forums
          • Question

          • User740222511 posted
            Hi All, I am load testing a web application built using ASP.Net and communicates with a Web services which uses oracle rdb odbc driver to connect to RDB server, but after a while I started getting this error when executing simple statements like insert or update
            against the database: Data : System.Collections.ListDictionaryInternal Source : SQRDB3.DLL Message : ERROR [08S01] [Oracle][ODBC][Rdb] send() Ret -1 Err#10038 WSAENOTSOCK File descriptor not a socket InnerException : Error: System.Data.Odbc.OdbcException:
            ERROR [08S01] [Oracle][ODBC][Rdb] send() Ret -1 Err#10038 WSAENOTSOCK File descriptor not a socket at System.Data.Odbc.OdbcConnection.HandleError(OdbcHa ndle hrHandle, RetCode retcode) at System.Data.Odbc.OdbcCommand.ExecuteReaderObject(C ommandBehavior behavior,
            String method, Boolean needReader, Object[] methodArguments, SQL_API odbcApiMethod) at System.Data.Odbc.OdbcCommand.ExecuteReaderObject(C ommandBehavior behavior, String method, Boolean needReader) at System.Data.Odbc.OdbcCommand.ExecuteNonQuery() Please Help
            Me, Thanks in advance..

          Понравилась статья? Поделить с друзьями:
        • Clickteam fusion file error
        • Clicking resolve error and then try to print again
        • Clickhouse коды ошибок
        • Clickhouse db exception syntax error multi statements are not allowed
        • Clickhouse create user syntax error