Citrix ошибка сокета 10038

Skip to content

Call Us Today! +35316877185|info@rgb.ie

Managed IT Services, Managed IT Solutions and IT Support Logo

Managed IT Services, Managed IT Solutions and IT Support Logo

Search for:

Citrix Socket Error 10038

Home/IT/Citrix Socket Error 10038

Previous Next
  • View Larger Image

Citrix Socket Error 10038

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

The dreaded message when using Citrix Receiver.

Happens with Citrix Receiver 4.11 and 4.12 – quickest solution is to remove the current version of Citrix Receiver and install Citrix Receiver 4.9 ( available here: https://www.citrix.com/downloads/citrix-receiver/legacy-receiver-for-windows/receiver-for-windows-49LTSR.html )

I’ve also uploaded a copy here: https://www.rgb.ie/citrix_receiver_v4.9.exe


More information

In March 2018, Microsoft announced a newly discovered vulnerability in the CredSSP protocol, which is used by Remote Desktop Connection to authenticate your password or smart card using Network Level Authentication (NLA). The flaw could allow someone to capture your credentials if he has access to the traffic between your client computer and the target. The above 10038 error occurs if one system is updated and the other system is not.

Best to patch those remote terminals! 🙂

By Media Team|2018-09-14T09:19:40+00:00September 14th, 2018|IT|3 Comments

About the Author: Media Team

Media & PR Team for Really Good Business.

All enquiries can be sent to pr@rgb.ie

Related Posts

  • Operation Triangulation – iOS devices targeted with previously unknown malware

    Operation Triangulation – iOS devices targeted with previously unknown malware

  • Microsoft 365

    Microsoft 365

    Gallery

    Microsoft 365

  • Managed IT Service Solutions

    Managed IT Service Solutions

    Gallery

    Managed IT Service Solutions

  • Panasonic KX UT Series – Reboot on attended transfer with 3CX V18 in the cloud

    Panasonic KX UT Series – Reboot on attended transfer with 3CX V18 in the cloud

    Gallery

    Panasonic KX UT Series – Reboot on attended transfer with 3CX V18 in the cloud

  • Hosted Phone Solutions, VoIP and Microsoft 365 Integration – UPGRADE TODAY!

    Hosted Phone Solutions, VoIP and Microsoft 365 Integration – UPGRADE TODAY!

    Gallery

    Hosted Phone Solutions, VoIP and Microsoft 365 Integration – UPGRADE TODAY!


3 Comments

  1. ytdfghg
    February 11, 2020 at 8:26 am — Reply

    thank you its working
    you save me

  2. Utkarsh Gupta
    April 6, 2020 at 7:27 pm — Reply

    Hi,

    Perfect solution to the problem. Resolved my critical issue.

  3. Rakshith
    April 8, 2020 at 9:33 am — Reply

    Same the socket error 10038 reflects .. please help me .. wat is the proceger I need to do .

Leave A Comment Cancel reply

Comment

Δ

Go to Top

Новичок

Профиль
Группа: Участник
Сообщений: 12
Регистрация: 8.4.2006

Репутация: нет
Всего: нет

у меня не хватает сил уже с этим кодом короче:
tcpclient.cpp

Код

// tcpclient.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "winsock2.h"
#include "stdio.h"
#include "windows.h"
#include "string.h"
#include "stdlib.h"
#pragma comment(lib, "ws2_32.lib")

int main()//int argc, char* argv[])
{
    sockaddr_in* sock_in_=new sockaddr_in;
    SOCKET sd;
    int port=80;
    char buff[1024];
    char ip[20];
    ZeroMemory(&ip, sizeof(ip)); 
    ZeroMemory(sock_in_, sizeof(sock_in_));
    strcpy(ip,"172.16.0.2");

    if (WSAStartup(0x202,(WSADATA *)&buff[0]))
    {
      printf("WSAStart error %dn",WSAGetLastError());
      free(sock_in_);
      return -1;
    }

    if ((sd=socket(AF_INET, SOCK_STREAM,0))<=0)
    {
      printf("Socket() error %dn",WSAGetLastError());
      free(sock_in_);
      return -1;
    }
    else printf("%sn","socket was create successful");
    sock_in_->sin_family=AF_INET;
    sock_in_->sin_port=htons(port);
    if (inet_addr(ip)!=INADDR_NONE)
    sock_in_->sin_addr.s_addr=inet_addr(ip);
    else
    {
    printf("Invalid address %sn",ip);
    closesocket(sd);
    free(sock_in_);
    WSACleanup();
    return -1;
    }
    int con=0;
    if ((con=connect(sd, (sockaddr *)sock_in_, sizeof(sock_in_)))!=0)
    {
      printf("Connect error %dn",WSAGetLastError());
      free(sock_in_);
      return -1;
    }
    printf("%sn%s", "The connetion successfull set", ip);
    ZeroMemory(&buff, sizeof(buff));
    int nsize;
    while((nsize=recv(sd,&buff[0],sizeof(buff)-1,0))!=SOCKET_ERROR)
    {
        buff[nsize]=0;
        printf("S=>C:%s",buff);
        printf("S<=C:"); fgets(&buff[0],sizeof(buff)-1,stdin);
    }
    send(sd,&buff[0],nsize,0);
    free(sock_in_);
    return 0;
}

tcpserver.cpp

Код

/*---------------Simple tcp echo server-----------------------*/    
#include "stdafx.h"    
#include "Winsock2.h"    
#include "Windows.h"    
#include "Winbase.h"    
#include "stdio.h"    
#include "WINSOCK.H"    
#include "string.h"    
#pragma comment(lib, "ws2_32.lib")    
int main()    
{    
    int sd;    
    int bindw;    
    struct sockaddr_in addr_in_;                 
    struct sockaddr asd;    
    ZeroMemory(&asd, sizeof(asd));    
    char buff[1024];    
    if (WSAStartup(0x202,(WSADATA *)&buff[0]))    
    {    
      printf("WSAStart error %dn",WSAGetLastError());    
      return -1;    
    }    
    if (sd=socket(AF_INET, SOCK_STREAM , 0)>=0)         
        printf("%sn", "the socket is successfull create");         
    else    
    {    
        printf("Error bind %dn",WSAGetLastError());    
        closesocket(sd);    
        WSACleanup();    
        return -1;    
    }    
    ZeroMemory(&addr_in_, sizeof(addr_in_));                 
    addr_in_.sin_family=AF_INET;                             
    addr_in_.sin_addr.s_addr=inet_addr("172.16.3.10");    
    addr_in_.sin_port=htons(8025);//argv[2];    
    if (bindw=bind(sd, (struct sockaddr *) &addr_in_, sizeof(addr_in_)))    
    {    
      printf("Error bind %dn",WSAGetLastError());    
      closesocket(sd);    
      WSACleanup();    
      return -1;    
    }    
    if (listen(sd, 20))                                
    {    
        printf("Error bind %dn",WSAGetLastError());    
        closesocket(sd);    
        WSACleanup();    
    }    
    printf("waiting connection...n");    
    for (;;)                                          
    {    
        int socksd;                                         
        int size=sizeof(addr_in_);    
        socksd = accept(sd, (struct sockaddr*) &addr_in_, &size);    
        if (socksd>0)                                     
        {    
            char buffer[1024];    
            int nbytes;    
            do    
            {    
                nbytes=recv(socksd,buffer,sizeof(buffer),0);    
                if (nbytes>0)                                     
                    send(socksd, buffer, sizeof(buffer), 0);     
            }    
            while(nbytes>0 && strncmp("byer", buffer, 4)!=0);     
            closesocket(socksd);                             
        }    
        printf("Error bind %dn",WSAGetLastError());    
        closesocket(sd);    
        WSACleanup();    
        exit(1);    
    }    
    closesocket(sd);    
    WSACleanup();    
        return 0;    
}    
/*----------------------------------------End of Source-----------------------------------------*/

все компилируеться, когда запускаю клиента выдает
Connect error 10014
описание ошибки:
WSAEFAULT (10014) Bad address.

Berkeley description: The system detected an invalid address in attempting to use an argument of a call.

WinSock description: Same as Berkeley, and then some. Specifically, v1.1 WinSock spec notes that this error occurs if the length of the buffer is too small. For instance, if the length of a struct sockaddr is not equivalent to the sizeof(struct sockaddr). However, it also occurs when an application passes an invalid pointer value.

Developer suggestions: Always check the return value from a memory allocation to be sure it succeeded. Always be sure to allocate enough space.

WinSock functions: accept(), bind(), connect(), gethostname(), getpeername(), getsockname(), getsockopt(), recvfrom(), send(), sendto(), setsockopt() if buffer length is too small.

Additional functions: Any functions that takes a pointer as an input parameter: inet_addr(), inet_ntoa(), ioctlsocket(), gethostbyaddr(), gethostbyname(), getservbyname(), getservbyport(), WSAAsyncGetHostByName(), WSAAsyncGetHostByAddr(), WSAAsyncGetProtoByName(), WSAAsyncGetProtoByNumber, WSAAsyncGetServByName(), WSAAsyncGetServByPort(), WSASetBlockingHook()

когда пускаю сервер
error bind 10038
я ее описал в 1-м посте

Компилировал программу на двох компах- итог одинsmile

Загнал исходник который мне любезно предоставил уважаемый 040375 в VC++ 6.0 при компиляции выдало:
fatal error C1010: unexpected end of file while looking for precompiled header directive

Может я не тот проект создаю, или … может где-то ошибка на елементарном уровне(ДНК не предлагатьsmile)

Customers who viewed this article also viewed

CTX238472


{{tooltipText}}

Article
|


Configuration

|

{{likeCount}} found this helpful
|

Created:
{{articleFormattedCreatedDate}}

|
Modified:
{{articleFormattedModifiedDate}}

Applicable Products

  • XenDesktop 7.18
  • Citrix Virtual Apps and Desktops

Symptoms or Error

After enabling SSL in Linux VDA, Citrix Workspace app fails to connect and displays the error «Unable to connect to the server. Contact your system administrator with the following error: Socket operation on non-socket (Socket Error 10038)»

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

There is an entry in hdx.log:

2018-09-26 16:16:54.240 <P30103> citrix-ctxhdx: TdCgpRead: Received an unknown packet on Port 443
2018-09-26 16:16:54.240 <P30103> citrix-ctxhdx: TdCgpRead: 0x16  0x03  0x01  0x00
2018-09-26 16:16:54.240 <P30103> citrix-ctxhdx: TdCgpRead: Bad State!! IcaState is 671, pTd is (nil)
2018-09-26 16:16:54.240 <P30103> citrix-ctxhdx: TdHandshakeThread: Handshake failed: CONNECTION_ABORTED, td state: 671

Solution

Ensure that the server certificate provided to
enable_vdassl.sh contains:

  • The Server Certificate
  • The Unencrypted Private Key
  • The Intermediate Certificates (if applicable)

For example:

# cat /etc/xdl/.sslkeystore/certs/server-certificate.pem
-----BEGIN CERTIFICATE-----
MIIFtDCCBJygAwIBAgITagAAAC/tYAov1PR7pwABAAAALzANBgkqhkiG9w0BAQsF
…
aC5qLjOGOe0iwqJgn4FTRvnIF59YKPa9
-----END CERTIFICATE-----
-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDBZarRkNJodsHU
…
GrYPz8Z8OU5FN58vEny9a6XF
-----END PRIVATE KEY-----

Problem Cause

There can be a number of causes of this issue, some of which are:

1. Encrypted Private Key

The server certificate contains an encrypted private key:

/etc/xdl/.sslkeystore/certs/
server-certificate.pem

-----BEGIN ENCRYPTED PRIVATE KEY-----
MIIFDjBABgkqhkiG9w0BBQ0wMzAbBgkqhkiG9w0BBQwwDgQIj6gr8yDIglQCAggA
…
lak=
-----END ENCRYPTED PRIVATE KEY-----
…

This will result in the additional dialogue from Desktop Viewer ‘The connection to »
Delivery Group Name» failed with status (Unknown client error 0).’:

Unknown client error 0

2. No Private Key

The server certificate contains no private key.

This will result in the additional dialogue from Desktop Viewer ‘The connection to »
Delivery Group Name» failed with status (Unknown client error 1110).’:

The connection to "Delivery Group Name" failed with status (Unknown client error 1110).

When
enable_vdassl.sh was run there would have been an error message included in the output:

Verifying the specified certificate /etc/xdl/.sslkeystore/certs/server-certificate.pem...
unable to load Private Key
140270488938384:error:0906D06C:PEM routines:PEM_read_bio:no start line:pem_lib.c:707:Expecting: ANY PRIVATE KEY


Was this page helpful?












Thank you!





Sorry to hear that.


Please provide
{{ feedbackPageLabel.toLowerCase() }} feedback.


Please provide article feedback


Feel free to give us additional feedback!


What can we do to improve this page?

Email

Email address is required

Please verify reCAPTCHA and press «Submit» button

Failed
to load featured products content, Please

try again

.

Skip to content

Call Us Today! +35316877185|info@rgb.ie

Managed IT Services, Managed IT Solutions and IT Support Logo

Managed IT Services, Managed IT Solutions and IT Support Logo

Citrix Socket Error 10038

Home/IT/Citrix Socket Error 10038

Previous Next

  • View Larger Image

Citrix Socket Error 10038

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

The dreaded message when using Citrix Receiver.

Happens with Citrix Receiver 4.11 and 4.12 – quickest solution is to remove the current version of Citrix Receiver and install Citrix Receiver 4.9 ( available here: https://www.citrix.com/downloads/citrix-receiver/legacy-receiver-for-windows/receiver-for-windows-49LTSR.html )

I’ve also uploaded a copy here: https://www.rgb.ie/citrix_receiver_v4.9.exe


More information

In March 2018, Microsoft announced a newly discovered vulnerability in the CredSSP protocol, which is used by Remote Desktop Connection to authenticate your password or smart card using Network Level Authentication (NLA). The flaw could allow someone to capture your credentials if he has access to the traffic between your client computer and the target. The above 10038 error occurs if one system is updated and the other system is not.

Best to patch those remote terminals! 🙂

By Media Team|2018-09-14T09:19:40+00:00September 14th, 2018|IT|3 Comments

About the Author: Media Team

Media & PR Team for Really Good Business.

All enquiries can be sent to pr@rgb.ie

Related Posts

  • Microsoft 365

    Microsoft 365

    Gallery

    Microsoft 365

  • Managed IT Service Solutions

    Managed IT Service Solutions

    Gallery

    Managed IT Service Solutions

  • Panasonic KX UT Series – Reboot on attended transfer with 3CX V18 in the cloud

    Panasonic KX UT Series – Reboot on attended transfer with 3CX V18 in the cloud

    Gallery

    Panasonic KX UT Series – Reboot on attended transfer with 3CX V18 in the cloud

  • Hosted Phone Solutions, VoIP and Microsoft 365 Integration – UPGRADE TODAY!

    Hosted Phone Solutions, VoIP and Microsoft 365 Integration – UPGRADE TODAY!

    Gallery

    Hosted Phone Solutions, VoIP and Microsoft 365 Integration – UPGRADE TODAY!

  • Windows 11 is here and it’s time to ugprade

    Windows 11 is here and it’s time to ugprade

    Gallery

    Windows 11 is here and it’s time to ugprade

3 Comments

  1. ytdfghg
    February 11, 2020 at 8:26 am — Reply

    thank you its working
    you save me

  2. Utkarsh Gupta
    April 6, 2020 at 7:27 pm — Reply

    Hi,

    Perfect solution to the problem. Resolved my critical issue.

  3. Rakshith
    April 8, 2020 at 9:33 am — Reply

    Same the socket error 10038 reflects .. please help me .. wat is the proceger I need to do .

Leave A Comment Cancel reply

Comment

Δ

Go to Top

Новичок

Профиль
Группа: Участник
Сообщений: 12
Регистрация: 8.4.2006

Репутация: нет
Всего: нет

у меня не хватает сил уже с этим кодом короче:
tcpclient.cpp

Код

// tcpclient.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "winsock2.h"
#include "stdio.h"
#include "windows.h"
#include "string.h"
#include "stdlib.h"
#pragma comment(lib, "ws2_32.lib")

int main()//int argc, char* argv[])
{
    sockaddr_in* sock_in_=new sockaddr_in;
    SOCKET sd;
    int port=80;
    char buff[1024];
    char ip[20];
    ZeroMemory(&ip, sizeof(ip)); 
    ZeroMemory(sock_in_, sizeof(sock_in_));
    strcpy(ip,"172.16.0.2");

    if (WSAStartup(0x202,(WSADATA *)&buff[0]))
    {
      printf("WSAStart error %dn",WSAGetLastError());
      free(sock_in_);
      return -1;
    }

    if ((sd=socket(AF_INET, SOCK_STREAM,0))<=0)
    {
      printf("Socket() error %dn",WSAGetLastError());
      free(sock_in_);
      return -1;
    }
    else printf("%sn","socket was create successful");
    sock_in_->sin_family=AF_INET;
    sock_in_->sin_port=htons(port);
    if (inet_addr(ip)!=INADDR_NONE)
    sock_in_->sin_addr.s_addr=inet_addr(ip);
    else
    {
    printf("Invalid address %sn",ip);
    closesocket(sd);
    free(sock_in_);
    WSACleanup();
    return -1;
    }
    int con=0;
    if ((con=connect(sd, (sockaddr *)sock_in_, sizeof(sock_in_)))!=0)
    {
      printf("Connect error %dn",WSAGetLastError());
      free(sock_in_);
      return -1;
    }
    printf("%sn%s", "The connetion successfull set", ip);
    ZeroMemory(&buff, sizeof(buff));
    int nsize;
    while((nsize=recv(sd,&buff[0],sizeof(buff)-1,0))!=SOCKET_ERROR)
    {
        buff[nsize]=0;
        printf("S=>C:%s",buff);
        printf("S<=C:"); fgets(&buff[0],sizeof(buff)-1,stdin);
    }
    send(sd,&buff[0],nsize,0);
    free(sock_in_);
    return 0;
}

tcpserver.cpp

Код

/*---------------Simple tcp echo server-----------------------*/    
#include "stdafx.h"    
#include "Winsock2.h"    
#include "Windows.h"    
#include "Winbase.h"    
#include "stdio.h"    
#include "WINSOCK.H"    
#include "string.h"    
#pragma comment(lib, "ws2_32.lib")    
int main()    
{    
    int sd;    
    int bindw;    
    struct sockaddr_in addr_in_;                 
    struct sockaddr asd;    
    ZeroMemory(&asd, sizeof(asd));    
    char buff[1024];    
    if (WSAStartup(0x202,(WSADATA *)&buff[0]))    
    {    
      printf("WSAStart error %dn",WSAGetLastError());    
      return -1;    
    }    
    if (sd=socket(AF_INET, SOCK_STREAM , 0)>=0)         
        printf("%sn", "the socket is successfull create");         
    else    
    {    
        printf("Error bind %dn",WSAGetLastError());    
        closesocket(sd);    
        WSACleanup();    
        return -1;    
    }    
    ZeroMemory(&addr_in_, sizeof(addr_in_));                 
    addr_in_.sin_family=AF_INET;                             
    addr_in_.sin_addr.s_addr=inet_addr("172.16.3.10");    
    addr_in_.sin_port=htons(8025);//argv[2];    
    if (bindw=bind(sd, (struct sockaddr *) &addr_in_, sizeof(addr_in_)))    
    {    
      printf("Error bind %dn",WSAGetLastError());    
      closesocket(sd);    
      WSACleanup();    
      return -1;    
    }    
    if (listen(sd, 20))                                
    {    
        printf("Error bind %dn",WSAGetLastError());    
        closesocket(sd);    
        WSACleanup();    
    }    
    printf("waiting connection...n");    
    for (;;)                                          
    {    
        int socksd;                                         
        int size=sizeof(addr_in_);    
        socksd = accept(sd, (struct sockaddr*) &addr_in_, &size);    
        if (socksd>0)                                     
        {    
            char buffer[1024];    
            int nbytes;    
            do    
            {    
                nbytes=recv(socksd,buffer,sizeof(buffer),0);    
                if (nbytes>0)                                     
                    send(socksd, buffer, sizeof(buffer), 0);     
            }    
            while(nbytes>0 && strncmp("byer", buffer, 4)!=0);     
            closesocket(socksd);                             
        }    
        printf("Error bind %dn",WSAGetLastError());    
        closesocket(sd);    
        WSACleanup();    
        exit(1);    
    }    
    closesocket(sd);    
    WSACleanup();    
        return 0;    
}    
/*----------------------------------------End of Source-----------------------------------------*/

все компилируеться, когда запускаю клиента выдает
Connect error 10014
описание ошибки:
WSAEFAULT (10014) Bad address.

Berkeley description: The system detected an invalid address in attempting to use an argument of a call.

WinSock description: Same as Berkeley, and then some. Specifically, v1.1 WinSock spec notes that this error occurs if the length of the buffer is too small. For instance, if the length of a struct sockaddr is not equivalent to the sizeof(struct sockaddr). However, it also occurs when an application passes an invalid pointer value.

Developer suggestions: Always check the return value from a memory allocation to be sure it succeeded. Always be sure to allocate enough space.

WinSock functions: accept(), bind(), connect(), gethostname(), getpeername(), getsockname(), getsockopt(), recvfrom(), send(), sendto(), setsockopt() if buffer length is too small.

Additional functions: Any functions that takes a pointer as an input parameter: inet_addr(), inet_ntoa(), ioctlsocket(), gethostbyaddr(), gethostbyname(), getservbyname(), getservbyport(), WSAAsyncGetHostByName(), WSAAsyncGetHostByAddr(), WSAAsyncGetProtoByName(), WSAAsyncGetProtoByNumber, WSAAsyncGetServByName(), WSAAsyncGetServByPort(), WSASetBlockingHook()

когда пускаю сервер
error bind 10038
я ее описал в 1-м посте

Компилировал программу на двох компах- итог одинsmile

Загнал исходник который мне любезно предоставил уважаемый 040375 в VC++ 6.0 при компиляции выдало:
fatal error C1010: unexpected end of file while looking for precompiled header directive

Может я не тот проект создаю, или … может где-то ошибка на елементарном уровне(ДНК не предлагатьsmile)

«Отладка и поиск неисправностей», «Список ошибок MyChat Client», «Сетевые ошибки», «#10038: socket operation on nonsocket».

Ошибка

Сетевая ошибка 10038: «Socket operation on nonsocket»

Описание ошибки

Вы пытаетесь работать с неоткрытым или уже закрытым сетевым сокетом.

Вы указываете неправильный или несуществующий адрес для bind серверного сокета.

Вы пытаетесь сделать bind IPv6 локального адреса для сокета, который работает на IPv4 или наоборот.

Решение проблемы

Проверьте корректность адреса серверного сокета для bind и его физическую доступность.

Unlike other platforms, Windows does not use file descriptors to represent sockets. It uses actual kernel objects. Other platforms use int to represent open file descriptors, and thus to represent sockets. Windows uses the SOCKET type instead, which is a typedef for UINT_PTR (unsigned int in 32bit, unsigned __int64 in 64bit) so it can accommodate object handles. The socket() function on Windows returns INVALID_SOCKET (which is (SOCKET)(~0)) on error, while other platforms return (int)-1 instead. You need to make sure you account for this so you do not slice/truncate legitimate socket handles on Windows.

When your client is calling inet_addr(), it is passing a char** where a char* is expected. Your compiler should have reported an error on that.

As sockets are not represented as file descriptors on Windows, you cannot use the read() and write() functions with Windows sockets. You must use the recv()/WSARecv() and send()/WSASend() functions instead. And you need to handle the case where the functions can return SOCKET_ERROR (-1) on error.

Try something more like this instead:

client :

#include <winsock.h>
#include <stdio.h>
#include <string.h>

#define BUFFSIZE 32

void DieWithErrorCode(char *errorMessage, int errCode);
void DieWithError(char *errorMessage, int *errCode = NULL);

int main(int argc, char* argv[])
{
    SOCKET sock;
    int ret;
    struct sockaddr_in servAddr;
    unsigned short servPort = 13;
    char *servIP;
    char buff[BUFFSIZE];
    WSADATA wsaData;

    if (argc != 2) {
        DieWithErrorCode("ERROR argc", WSAEINVAL);
    }
    servIP = argv[1];

    ret = WSAStartup(MAKEWORD(2,0), &wsaData);
    if (ret != 0) {
        DieWithErrorCode("ERROR WSAStartup", ret);
    }

    sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (sock == INVALID_SOCKET) {
        DieWithError("ERROR socket");
    }

    memset(&servAddr, 0, sizeof(servAddr));
    servAddr.sin_family = AF_INET;
    servAddr.sin_port = htons(servPort);
    servAddr.sin_addr.s_addr = inet_addr(servIP);
    if (servAddr.sin_addr.s_addr == INET_NONE) {
        DieWithErrorCode("ERROR inet_addr", WSAEINVAL);
    }

    if (connect(sock, (struct sockaddr *)&servAddr, sizeof(servAddr)) == SOCKET_ERROR) {
        DieWithError("ERROR connect");
    }

    while(1) {
        ret = recv(sock, buff, BUFFSIZE, 0);
        if (ret == SOCKET_ERROR) {
            DieWithError("ERROR recv");
        }

        if (ret == 0) {
            fprintf(stderr, "disconnectedn");
            break;
        }

        printf("Heure : %.*sn", ret, buff);
    }

    closesocket(sock);
    WSACleanup();

    return 0;
}

void DieWithErrorCode(char *errorMessage, int errCode)
{
    fprintf(stderr, "%s: %dn", errorMessage, errCode);
    exit(1);
}

void DieWithError(char *errorMessage)
{
    DieWithErrorCode(errorMessage, WSAGetLastError());
}

server:

#include <winsock.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <stdlib.h>

#define MAXLINE 32

void DieWithErrorCode(char *errorMessage, int errCode);
void DieWithError(char *errorMessage);

int main()
{
    SOCKET sock, sockc;
    struct sockaddr_in servAddr;
    unsigned short servPort = 13;
    time_t ticks;
    WSADATA wsaData;
    char buff[MAXLINE];
    int ret, buflen;

    ret = WSAStartup(MAKEWORD(2,0), &wsaData);
    if (ret != 0) {
        DieWithErrorCode("ERROR WSA", ret);
    }

    sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (sock == INVALID_SOCKET) {
        DieWithError("ERROR socket");
    }

    memset(&servAddr, 0, sizeof(servAddr));
    servAddr.sin_family = AF_INET;
    servAddr.sin_port = htons(servPort);
    servAddr.sin_addr.s_addr = htonl(INADDR_ANY);

    if (bind(sock, (struct sockaddr *)&servAddr, sizeof(servAddr)) == SOCKET_ERROR) {
        DieWithError("ERROR bind");
    }

    if (listen(sock, MAXQUEUE) == SOCKET_ERROR) {
        DieWithError("ERROR listen");
    }

    while(1) {
        sockc = accept(sock, NULL, NULL);
        if (sockc == INVALID_SOCKET) {
            DieWithError("ERROR accept");
        }

        ticks = time(NULL);
        buflen = snprintf(buff, sizeof(buff), "%s", ctime(&ticks));
        if (send(sockc, buff, buflen, 0) == SOCKET_ERROR) {
            fprintf(stderr, "ERROR send: %dn", WSAGetLastError());
        }

        closesocket(sockc);
    }

    closesocket(sock);
    WSACleanup();

    return 0;
}

void DieWithErrorCode(char *errorMessage, int errCode)
{
    fprintf(stderr,"%s: %dn", errorMessage, errCode);
    exit(1);
}

void DieWithError(char *errorMessage)
{
    DieWithErrorCode(char *errorMessage, WSAGetLastError());
}

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

9806 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

294k43 gold badges465 silver badges540 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.4k9 gold badges91 silver badges140 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 badges36 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

    msm.ru

    Нравится ресурс?

    Помоги проекту!

    [!] Как относитесь к модерированию на этом форуме? Выскажите свое мнение здесь

    >
    Сокет и ошибка 10038

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



    Сообщ.
    #1

    ,
    04.09.08, 11:29

      Full Member

      ***

      Рейтинг (т): 7

      День добрый.
      Вообщем история такая. Есть два приложения — клиент и сервер. Вообщем всё классически. Трабл такого толка — когда клиент закрывает соединение на сервере сразу же после обработчика события OnClientDisconnect вываливается ошибка:
      Windows socket error: Сделана попытка выполнить операцию на объекте, не являющемся сокетом (10038), on API ‘closesocket’
      При чём вываливается сразу в двух экземплярах. Код огромный — выкладывать его тут смысла нет. Вероятно на момент закрытия сокета он уже не существует исходя из толкования ошибки. С другой стороны он передаётся в обработчик, так что существовать должен, в дебаге видно даже его настройки. Проверено, что никакой другой кусок кода в этот момент не пытается работать с этим сокетом. Мысли есть?

      Добавлено 04.09.08, 12:14
      Прошерстил гугль. Указанная ошибка встречается всего два раза. Оба пальцем в небо.


      trainer



      Сообщ.
      #2

      ,
      04.09.08, 13:09

        Цитата DrMort @ 04.09.08, 11:29

        С другой стороны он передаётся в обработчик, так что существовать должен, в дебаге видно даже его настройки.

        Какое отношение обработчик события в компоненте VCL имеет к системному объекту? Системный объект видимо удален, экземпляр компонента остался. Любые попытки использовать системный объект через компонент будут давать ошибки(если компонент не будет самостоятельно пересоздавать системный объект, а он в данном случае не будет пересоздавать).
        Ну и исходник покажи.
        Хотя вообще-то странно. Не должен на сервере закрываться сокет, находящийся в режиме прослушивания.

        Эээ… Ты закрываешь сокет в OnClientDisconnect?

        Сообщение отредактировано: trainer — 04.09.08, 13:17


        Akme



        Сообщ.
        #3

        ,
        04.09.08, 13:17

          Указатели какие-нить не перезаписываешь? Что в дисконекте делается? Один поток в программе или нет?


          DrMort



          Сообщ.
          #4

          ,
          05.09.08, 01:20

            Full Member

            ***

            Рейтинг (т): 7

            Никаких указателей не перезаписываю. В дисконнекте меняются просто флажки соединений — то есть в массив проставляется что васе пупкину больше ничего отсылать не стоит — мы его потеряли. Программа однопоточная — никаких специальных замутов наподобии CreateThread не делал. Сейчас попробую привести некий кусок кода

            ExpandedWrap disabled

              void __fastcall TForm1::ServerSocket1ClientDisconnect(TObject *Sender,

                    TCustomWinSocket *Socket)

              {

                      int CurrentLocation=0,counter=0;

                      int NumSym=0,i,o;

                      AnsiString CurrName=»»;

                      for(i=0;i<MaxConnections;i++) //MaxConnections — константа содержащая максимальное число соединений с клиентами

                              {

                              if((Connections[i].Socket==Socket) && (Connections[i].Connected==true))

                                      {

                                      if(Connections[i].Login!=»»)

                                              {

                                              Memo1->Lines->Add(Connections[i].Login+» disconnected»);

                                              CurrName=Connections[i].Login;

                                              CurrName=CurrName.Trim();

                                              }

                                      else

                                              Memo1->Lines->Add(«Non logined client disconnected»);

                                      Connections[i].Connected=false;

                                      Connections[i].Autorize=false;

                                      for(o=0;o<BufferLength;o++)

                                              Connections[i].SendBuffer[o]=»»;

                                      Connections[i].BufferCounter=0;

                                      Connections[i].Idle=0;

                                      Form1->StatisticMonitor->Values[«CurrentConnection»]=IntToStr(StrToInt(Form1->StatisticMonitor->Values[«CurrentConnection»])-1);

                                      break;

                                      };

                              };

              }

            Connections[] — массив структур содержащий сведения о соединениях, В нём есть поле Socket значение которого заполняется при установке связи.

            Но все это описание зряшное, потомучто содержимое обработчика можно полностью убрать и ничего не изменится — проверено. Так же пробовал в начале каждой процедуры имеющейся в проекте ставить стоп поинт и отслеживать что ещё происходит в момент когда клиент обрывает связь. Так вот ничего не происходит — сразу срабатывает OnClientDisconnect. Сразу после его срабатывания вылетает подряд две ошибки. Так что вероятнее всего дело не в исходном коде, а в настройках/багах проекта/операционной системы/среды программирования. Чуть позже попробую на чистом компе возвести SQL сервер и запустить серверное приложение. Если ошибка исчезнет — всему виной срада/операционка.


            leo



            Сообщ.
            #5

            ,
            05.09.08, 07:28

              Цитата DrMort @ 05.09.08, 01:20

              В дисконнекте меняются просто флажки соединений — то есть в массив проставляется что васе пупкину больше ничего отсылать не стоит — мы его потеряли

              И что разорванное соединение так и остается навсегда в массиве Connections или удаляется ?
              Следует иметь в виду, что клиентский сокет закрывается и удаляется автоматически после вызова OnClientDisconnect. Поэтому ни закрывать, ни освобождать самому Connections[i].Socket в OnClientDisconnect (и тем более до или после) нельзя, ну и ес-но нельзя обращаться к инвалидному указателю Connections[i].Socket после OnClientDisconnect

              Цитата DrMort @ 05.09.08, 01:20

              Программа однопоточная — никаких специальных замутов наподобии CreateThread не делал

              Чтобы прога стало многопоточной достаточно установить «замут» ServerType:=stThreadBlocking ;)


              DrMort



              Сообщ.
              #6

              ,
              05.09.08, 10:26

                Full Member

                ***

                Рейтинг (т): 7

                Разорваное соединение остаётся, но никогда не используется. По прошествии некоторого времени по таймеру выбираются все разорваные соединения и удаляются из массива.
                Ещё раз — в OnClientDisconnect сокет вообще не трогается — процедура обработчика вообще может быть пустой. И тем более к указателю Connections[i].Socket никто не обращается. Дело все таки несколько в другом.
                Про ServerType:=stThreadBlocking мне тоже известно.
                Попробовал запустить сервер на другом компе где поднят SQL. Запустилась и нормально работает. Переставил винду. У меня по прежнему глючит. Возможно проблема с каким то драйвером. Мучаю дальше.


                Oleg2004



                Сообщ.
                #7

                ,
                05.09.08, 11:54

                  Есть такая ситуация — что в режиме дебага многие среды при тестирование клиент-серверных приложений глючат.
                  Поэтому я всегда рекомендую делать отладочные релизы и запускать как самостоятельные программы вне среды программирования……


                  DrMort



                  Сообщ.
                  #8

                  ,
                  05.09.08, 11:59

                    Full Member

                    ***

                    Рейтинг (т): 7

                    Вне среды все равно глючит. Переставил винду — все та же ошибка. Завтра попробую переставить винду и не ставить ни одного драйвера.


                    DrMort



                    Сообщ.
                    #9

                    ,
                    06.09.08, 08:31

                      Full Member

                      ***

                      Рейтинг (т): 7

                      Переставил винду поверх старой. Глючит. Форматнул винт — нормально. С дровами тоже нормально. Похоже что-то было с операционкой, может какие нить последствия лечения вирусни. Всем спасибо за мысли.

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

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

                      • Предыдущая тема
                      • Borland C++ Builder/Turbo C++ Explorer
                      • Следующая тема

                      Рейтинг@Mail.ru

                      [ Script execution time: 0,0311 ]   [ 16 queries used ]   [ Generated: 21.06.23, 18:42 GMT ]  

                    • Citrix workspace ошибка 3500
                    • Citrix workspace ошибка 2517
                    • Citrix receiver ошибка сертификата
                    • Citrix receiver ошибка ssl47
                    • Citrix receiver не удается запустить приложение ошибка драйвера протокола