![]()
![]()
Citrix Socket Error 10038
-
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! 🙂
About the Author: Media Team
All enquiries can be sent to pr@rgb.ie
Related Posts
-

Microsoft 365
Gallery
Microsoft 365
-

Managed IT Service Solutions
Gallery
Managed IT Service Solutions
-

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!
Gallery
Hosted Phone Solutions, VoIP and Microsoft 365 Integration – UPGRADE TODAY!
-

Windows 11 is here and it’s time to ugprade
Gallery
Windows 11 is here and it’s time to ugprade
3 Comments
-
ytdfghg
February 11, 2020 at 8:26 am — Replythank you its working
you save me -
Utkarsh Gupta
April 6, 2020 at 7:27 pm — ReplyHi,
Perfect solution to the problem. Resolved my critical issue.
-
Rakshith
April 8, 2020 at 9:33 am — ReplySame the socket error 10038 reflects .. please help me .. wat is the proceger I need to do .
Leave A Comment Cancel reply
Δ
Go to Top
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

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:

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»}}]
|
|
|
|
[!] Как относитесь к модерированию на этом форуме? Выскажите свое мнение здесь

Сокет и ошибка 10038
- Подписаться на тему
- Сообщить другу
- Скачать/распечатать тему
|
|
|
|
Full Member
Рейтинг (т): 7 |
День добрый. Добавлено 04.09.08, 12:14 |
|
trainer |
|
|
Цитата DrMort @ 04.09.08, 11:29 С другой стороны он передаётся в обработчик, так что существовать должен, в дебаге видно даже его настройки. Какое отношение обработчик события в компоненте VCL имеет к системному объекту? Системный объект видимо удален, экземпляр компонента остался. Любые попытки использовать системный объект через компонент будут давать ошибки(если компонент не будет самостоятельно пересоздавать системный объект, а он в данном случае не будет пересоздавать). Эээ… Ты закрываешь сокет в OnClientDisconnect? Сообщение отредактировано: trainer — 04.09.08, 13:17 |
|
Akme |
|
|
Указатели какие-нить не перезаписываешь? Что в дисконекте делается? Один поток в программе или нет? |
|
DrMort |
|
|
Full Member
Рейтинг (т): 7 |
Никаких указателей не перезаписываю. В дисконнекте меняются просто флажки соединений — то есть в массив проставляется что васе пупкину больше ничего отсылать не стоит — мы его потеряли. Программа однопоточная — никаких специальных замутов наподобии CreateThread не делал. Сейчас попробую привести некий кусок кода
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 |
|
|
Цитата DrMort @ 05.09.08, 01:20 В дисконнекте меняются просто флажки соединений — то есть в массив проставляется что васе пупкину больше ничего отсылать не стоит — мы его потеряли
И что разорванное соединение так и остается навсегда в массиве Connections или удаляется ? Цитата DrMort @ 05.09.08, 01:20 Программа однопоточная — никаких специальных замутов наподобии CreateThread не делал
Чтобы прога стало многопоточной достаточно установить «замут» ServerType:=stThreadBlocking |
|
DrMort |
|
|
Full Member
Рейтинг (т): 7 |
Разорваное соединение остаётся, но никогда не используется. По прошествии некоторого времени по таймеру выбираются все разорваные соединения и удаляются из массива. |
|
Oleg2004 |
|
|
Есть такая ситуация — что в режиме дебага многие среды при тестирование клиент-серверных приложений глючат. |
|
DrMort |
|
|
Full Member
Рейтинг (т): 7 |
Вне среды все равно глючит. Переставил винду — все та же ошибка. Завтра попробую переставить винду и не ставить ни одного драйвера. |
|
DrMort |
|
|
Full Member
Рейтинг (т): 7 |
Переставил винду поверх старой. Глючит. Форматнул винт — нормально. С дровами тоже нормально. Похоже что-то было с операционкой, может какие нить последствия лечения вирусни. Всем спасибо за мысли. |
0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)
0 пользователей:
- Предыдущая тема
- Borland C++ Builder/Turbo C++ Explorer
- Следующая тема
[ Script execution time: 0,0438 ] [ 16 queries used ] [ Generated: 28.01.23, 17:23 GMT ]
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
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 WheatMitch Wheat
293k43 gold badges462 silver badges537 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 TownsendSteve Townsend
53.1k9 gold badges91 silver badges139 bronze badges
There may be two reasons for this:
- Your socket descriptor in uninitialized (i.e. doesn’t reference a valid socket).
- 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
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 WTed W
2394 silver badges11 bronze badges
1
Я пытаюсь настроить простое соединение с серверным приложением, работающим на том же компьютере, что и клиент.
Мой код выглядит так:
void Base::Connect(string ip, string port)
{
int status;
SOCKET ConnectSocket = INVALID_SOCKET;
struct addrinfo hints;
struct addrinfo *servinfo; // will point to the results
memset(&hints, 0, sizeof hints); // make sure the struct is empty
hints.ai_family = AF_UNSPEC; // don't care IPv4 or IPv6
hints.ai_socktype = SOCK_STREAM; // TCP stream sockets
// get ready to connect
status = getaddrinfo(ip.c_str(), port.c_str(), &hints, &servinfo);
// Socket Setup
if (ConnectSocket = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol) == INVALID_SOCKET)
{
printf("[NETWORKING] An error occured when setting up socketn");
}
// Connect
if (connect(ConnectSocket, servinfo->ai_addr, (int)servinfo->ai_addrlen) == SOCKET_ERROR)
{
int error = WSAGetLastError();
printf("Connect error: ", error);
}
}
Заранее звоню WSAStartup() и это не выдает никаких ошибок. Если сервер включен или выключен, ошибка не меняется.
Я использую IP-адрес 127.0.0.1, и я подключаюсь через порт 80. Я пробовал что-то еще (1337), которое выдало мне ту же ошибку.
Что-то явно не так? Любые идеи о том, что может пойти не так?
0
Решение
if (ConnectSocket = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol) == INVALID_SOCKET)
Вы сравниваете сокет (…) с INVALID_SOCKET
и затем вы назначаете результат true / false для ConnectSocket.
использование
if ((ConnectSocket = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol)) == INVALID_SOCKET)
Смотрите списки приоритетов операторов C ++
2
Другие решения
Других решений пока нет …

Форум программистов Vingrad
|
Модераторы: feodorv
|
Поиск: |
![]() ![]()
|
|
Опции темы |
| L0n3R4ng3r |
|
||
|
Новичок Профиль Репутация: нет
|
Вообщем обстоятельства и желания заставили меня учить работу с сокетами, почитав немого книжечку про создания сетевых приложения в Линуксе и порывшись в гугле и MSDN, я написал вот такое вот чудо:
когда запучтил он мне выдало ошибку 10038, поюзал гугл нашел описание ошибки: /*—————————————Описание ошибки————————————-*/ 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). Короче сам я разобраться не смог Это сообщение отредактировал(а) L0n3R4ng3r — 8.4.2006, 20:40 |
||
|
|||
| 040375 |
|
||
|
Новичок Профиль Репутация: 2
|
Ваша ошибка уважаемый в невнимательности и неправильном применении операции присваивания! |
||
|
|||
| L0n3R4ng3r |
|
||
|
Новичок Профиль Репутация: нет
|
забыл дописать что программирую я в среде Windows на Visual C++6.0 …это так лирическое отступления… исправил действительно sd было равно 1, сейчас ==1956, но существенно ничего не поменялось, ошибка таже самая что и была Это сообщение отредактировал(а) L0n3R4ng3r — 9.4.2006, 23:45 |
||
|
|||
| 040375 |
|
||
|
Новичок Профиль Репутация: 2
|
Я понял по коду — что вы работаете в студио. После некоторых исправлений я скомпилировал в Visual C++ и успешно запустил Ваш код — ошибок там почти нет. Программа работает. |
||
|
|||
| 040375 |
|
||
|
Новичок Профиль Репутация: 2
|
Я не смог Вам сразу указать ошибку ещё одну — по той простой причине, что ввёл несколько struct sockaddr_in addr_in_; — можно конечно и так как Вы написали — но в целях переносимости кода принято писать так. А вот строка — из-за которой неверно задавался адрес сокета: Заменил её на: |
||
|
|||
| L0n3R4ng3r |
|
||
|
Новичок Профиль Репутация: нет
|
Вообщем может я что-то не то поменял но у меня не опять таже ошибка
|
||
|
|||
| 040375 |
|
||
|
Новичок Профиль Репутация: 2
|
Привожу весь Ваш код. Не касаясь тонкостесь и приёмов разработки сетевых приложений всё работает.
|
||
|
|||
| L0n3R4ng3r |
|
||||
|
Новичок Профиль Репутация: нет
|
у меня не хватает сил уже с этим кодом короче:
tcpserver.cpp
все компилируеться, когда запускаю клиента выдает 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() когда пускаю сервер Компилировал программу на двох компах- итог один Загнал исходник который мне любезно предоставил уважаемый 040375 в VC++ 6.0 при компиляции выдало: Может я не тот проект создаю, или … может где-то ошибка на елементарном уровне(ДНК не предлагать |
||||
|
|||||
| 040375 |
|
||
|
Новичок Профиль Репутация: 2
|
Уважаемый, я вижу только одну проблему в Вашем коде. Прежде, чем садиться писать сетевые клиент-серверные приложения, советую обратить хоть какое то внимание на основы языка C. ZeroMemory(&ip, sizeof(ip)); такое разрешено — но опять же — принято, что название массива ZeroMemory(sock_in_, sizeof(sock_in_)); — здесь Вы обнуляете только первые 4 байта зачем-то динамически созданной структуры sockaddr_in free(sock_in_) — если Вы создаёте структуру динамически с помощью new, то удалять следует с помощью delete, free освобождает память после malloc и т.п. … Теперь что кается моего (Вашего поправленного) кода — как я уже сказал, я его запускал и он работает без ошибок (по крайней мере вышеназванных). Просто Вы скопировали его в редакторе |
||
|
|||
| L0n3R4ng3r |
|
||
|
Новичок Профиль Репутация: нет
|
спасибо за помощь, после этого поста все начало работать |
||
|
|||



















![]() ![]()
|
| 0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей) |
| 0 Пользователей: |
| « Предыдущая тема | C/C++: Сети | Следующая тема » |
I am testing out a Socket Server application in c and I am getting an error on the bind function with code 10038. I looked this up and MSDN says it means:
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.
Here is the code:
// I have the correct include files such as include , but stackoverflow displays it weird when i put #include winsock2.h
int main()
{
WSADATA wsaData;
SOCKET ListeningSocket;
SOCKET NewConnection;
SOCKADDR_IN ServerAddr;
int Port = 5150;
if(WSAStartup(MAKEWORD(2,2),&wsaData) != 0)
{
printf("Server: WSAStartup failed with error %ldn",WSAGetLastError());
return -1;
}
else
{
printf("Server: The Winsock dll found!n");
printf("Server: The current status is: %s.n",wsaData.szSystemStatus);
}
if(LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2)
{
printf("Server: The dll do not support Winsock version
%u.%u!n",LOBYTE(wsaData.wVersion),HIBYTE(wsaData.wVersion));
WSACleanup();
return -1;
}
else
{
printf("Server: The dll supports the Winsock version %u.%u!n",LOBYTE(wsaData.wVersion),HIBYTE(wsaData.wVersion));
printf("Server: The highest version this dll can support: %u.%un",LOBYTE(wsaData.wHighVersion),HIBYTE(wsaData.wHighVersion));
}
ListeningSocket == socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(ListeningSocket == INVALID_SOCKET)
{
printf("Server: Error at socket(), error code: %ldn",WSAGetLastError());
WSACleanup();
return -1;
}
else
printf("Server: socket() is OK!n");
ServerAddr.sin_family = AF_INET;
ServerAddr.sin_port = htons(Port);
ServerAddr.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(ListeningSocket, (SOCKADDR *)&ServerAddr,sizeof(ServerAddr)) == SOCKET_ERROR)
{
printf("Server: bind() failed! Error code: %ld.n",WSAGetLastError());
closesocket(ListeningSocket);
WSACleanup();
return -1;
}
else
printf("Server: bind() is OK!n");
if(listen(ListeningSocket,5) == SOCKET_ERROR)
{
printf("Server: listen(): Error listening on socket %ld.n", WSAGetLastError());
closesocket(ListeningSocket);
WSACleanup();
return -1;
}
else
printf("Server: listen() is OK, I'm waiting for connections...n");
printf("Server: accept() is ready...n");
while(1)
{
NewConnection = SOCKET_ERROR;
while(NewConnection == SOCKET_ERROR)
{
NewConnection = accept(ListeningSocket, NULL, NULL);
}
printf("Server: accept() is OK...n");
printf("Server: Client connected, ready for receiving and sending data...n");
ListeningSocket = NewConnection;
break;
}
if(closesocket(NewConnection) != 0)
printf("Server: Cannot close "NewConnection" socket. Error code: %ldn",
WSAGetLastError());
else
printf("Server: Closing "NewConnection" socket...n");
if(WSACleanup() != 0)
printf("Server: WSACleanup() failed! Error code: %ldn", WSAGetLastError());
else
printf("Server: WSACleanup() is OK...n");
return 0;
}
I am testing out a Socket Server application in c and I am getting an error on the bind function with code 10038. I looked this up and MSDN says it means:
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.
Here is the code:
// I have the correct include files such as include , but stackoverflow displays it weird when i put #include winsock2.h
int main()
{
WSADATA wsaData;
SOCKET ListeningSocket;
SOCKET NewConnection;
SOCKADDR_IN ServerAddr;
int Port = 5150;
if(WSAStartup(MAKEWORD(2,2),&wsaData) != 0)
{
printf("Server: WSAStartup failed with error %ldn",WSAGetLastError());
return -1;
}
else
{
printf("Server: The Winsock dll found!n");
printf("Server: The current status is: %s.n",wsaData.szSystemStatus);
}
if(LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2)
{
printf("Server: The dll do not support Winsock version
%u.%u!n",LOBYTE(wsaData.wVersion),HIBYTE(wsaData.wVersion));
WSACleanup();
return -1;
}
else
{
printf("Server: The dll supports the Winsock version %u.%u!n",LOBYTE(wsaData.wVersion),HIBYTE(wsaData.wVersion));
printf("Server: The highest version this dll can support: %u.%un",LOBYTE(wsaData.wHighVersion),HIBYTE(wsaData.wHighVersion));
}
ListeningSocket == socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(ListeningSocket == INVALID_SOCKET)
{
printf("Server: Error at socket(), error code: %ldn",WSAGetLastError());
WSACleanup();
return -1;
}
else
printf("Server: socket() is OK!n");
ServerAddr.sin_family = AF_INET;
ServerAddr.sin_port = htons(Port);
ServerAddr.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(ListeningSocket, (SOCKADDR *)&ServerAddr,sizeof(ServerAddr)) == SOCKET_ERROR)
{
printf("Server: bind() failed! Error code: %ld.n",WSAGetLastError());
closesocket(ListeningSocket);
WSACleanup();
return -1;
}
else
printf("Server: bind() is OK!n");
if(listen(ListeningSocket,5) == SOCKET_ERROR)
{
printf("Server: listen(): Error listening on socket %ld.n", WSAGetLastError());
closesocket(ListeningSocket);
WSACleanup();
return -1;
}
else
printf("Server: listen() is OK, I'm waiting for connections...n");
printf("Server: accept() is ready...n");
while(1)
{
NewConnection = SOCKET_ERROR;
while(NewConnection == SOCKET_ERROR)
{
NewConnection = accept(ListeningSocket, NULL, NULL);
}
printf("Server: accept() is OK...n");
printf("Server: Client connected, ready for receiving and sending data...n");
ListeningSocket = NewConnection;
break;
}
if(closesocket(NewConnection) != 0)
printf("Server: Cannot close "NewConnection" socket. Error code: %ldn",
WSAGetLastError());
else
printf("Server: Closing "NewConnection" socket...n");
if(WSACleanup() != 0)
printf("Server: WSACleanup() failed! Error code: %ldn", WSAGetLastError());
else
printf("Server: WSACleanup() is OK...n");
return 0;
}











