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,0403 ] [ 16 queries used ] [ Generated: 12.02.23, 04:29 GMT ]
Содержание
- Ошибка socket error 10038
- Why do I receive «FLEXlm error: -15,570. System Error: 10038 Winsock: Specified socket is invalid» when I try to start MATLAB?
- Direct link to this question
- Direct link to this question
- Accepted Answer
- Direct link to this answer
- Direct link to this answer
- More Answers (0)
- See Also
- Categories
- Products
- Community Treasure Hunt
- How to Get Best Site Performance
- Americas
- Europe
- Asia Pacific
- How Socket Error Codes Depend on Runtime and Operating System
- Digging into the problem
- SocketErrorCode
- NativeErrorCode
- ErrorCode
- Writing cross-platform socket error handling
- Overview of the native error codes
- Why do I receive «FLEXlm error: -15,570. System Error: 10038 Winsock: Specified socket is invalid» when I try to start MATLAB?
- Direct link to this question
- Direct link to this question
- Accepted Answer
- Direct link to this answer
- Direct link to this answer
- More Answers (0)
- See Also
- Categories
- Products
- Community Treasure Hunt
- How to Get Best Site Performance
- Americas
- Europe
- Asia Pacific
Ошибка socket error 10038
Please contact us if you have any trouble resetting your password.
The problem is that you increment the client count *before* you assign to the array. This causes assignment to the wrong slot, which means you pass a not-a-socket value into select(). 10038 means «not a socket» which makes sense.
Also, incrementing the counter first means that you have a potential buffer overrun. And, just because listen() takes 9 as a parameter, doesn’t mean that the number of potential connections will be limited to 9 — the *backlog* may be limited to 9. You could get 100 connections, and you’d totally crash your server. Or, worse, someone might exploit it as a remote code execution vulnerability.
Is this what you mean my ‘client count’:
If so, couldn’t I just put an if around it? Like this:
Quote: Original post by Azjherben
couldn’t I just put an if around it? Like this:
The if statement doesn’t do anything. If numclients is less than or equal to zero, the loop won’t execute (0 Cancel Save
You did not actually show the area where you increment the client count.
Specifically, you keep the client count in the «numclients» variable.
This is meant as good advice, not as a put-down: If you can’t figure out this simple problem from the information we’ve already given you, you should not be writing network code in C++ yet — you need to first learn the language really well, because distributed concurrent programming is hard as it is even when you’re fully fluent in developing in the language of your choice.
Quote: Original post by hplus0603
The problem is that you increment the client count *before* you assign to the array. This causes assignment to the wrong slot, which means you pass a not-a-socket value into select(). 10038 means «not a socket» which makes sense.
Also, incrementing the counter first means that you have a potential buffer overrun. And, just because listen() takes 9 as a parameter, doesn’t mean that the number of potential connections will be limited to 9 — the *backlog* may be limited to 9. You could get 100 connections, and you’d totally crash your server. Or, worse, someone might exploit it as a remote code execution vulnerability.
Okay, looking at what you said, I realize that I should have it check for the lowest number available out of the maximium amount (9) and set it to that. And have clients br removed from the array when they disconnect. (Making that number available again) As for the main error, I’ll try to fix that first. If I get a completly new error, or it works, I’ll post. Also, that for right after the while, that is what you mean by ‘client count’ right.
Источник
Why do I receive «FLEXlm error: -15,570. System Error: 10038 Winsock: Specified socket is invalid» when I try to start MATLAB?
Direct link to this question
Direct link to this question
Accepted Answer
Direct link to this answer
Direct link to this answer
0 Comments
More Answers (0)
See Also
Categories
No tags entered yet.
Products
Find the treasures in MATLAB Central and discover how the community can help you!
An Error Occurred
Unable to complete the action because of changes made to the page. Reload the page to see its updated state.
Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .
You can also select a web site from the following list:
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
Americas
Europe
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- Deutsch
- English
- Français
- United Kingdom (English)
Asia Pacific
- Australia (English)
- India (English)
- New Zealand (English)
- 中国
- 简体中文 Chinese
- English
- 日本 Japanese (日本語)
- 한국 Korean (한국어)
Accelerating the pace of engineering and science
MathWorks is the leading developer of mathematical computing software for engineers and scientists.
Источник
How Socket Error Codes Depend on Runtime and Operating System
Rider consists of several processes that send messages to each other via sockets. To ensure the reliability of the whole application, it’s important to properly handle all the socket errors. In our codebase, we had the following code which was adopted from Mono Debugger Libs and helps us communicate with debugger processes:
In the case of a failed connection because of a “ConnectionRefused” error, we are retrying the connection attempt. It works fine with .NET Framework and Mono. However, once we migrated to .NET Core, this method no longer correctly detects the “connection refused” situation on Linux and macOS. If we open the SocketException documentation, we will learn that this class has three different properties with error codes:
- SocketError SocketErrorCode : Gets the error code that is associated with this exception.
- int ErrorCode : Gets the error code that is associated with this exception.
- int NativeErrorCode : Gets the Win32 error code associated with this exception.
What’s the difference between these properties? Should we expect different values on different runtimes or different operating systems? Which one should we use in production? Why do we have problems with ShouldRetryConnection on .NET Core? Let’s figure it all out!
Digging into the problem
If we run it on Windows, we will get the same value on .NET Framework, Mono, and .NET Core:
SocketErrorCode | ErrorCode | NativeErrorCode | |
.NET Framework | 10061 | 10061 | 10061 |
Mono | 10061 | 10061 | 10061 |
.NET Core | 10061 | 10061 | 10061 |
10061 corresponds to the code of the connection refused socket error code in Windows (also known as WSAECONNREFUSED ). Now let’s run the same program on Linux:
SocketErrorCode | ErrorCode | NativeErrorCode | |
Mono | 10061 | 10061 | 10061 |
.NET Core | 10061 | 111 | 111 |
As you can see, Mono returns Windows-compatible error codes. The situation with .NET Core is different: it returns a Windows-compatible value for SocketErrorCode (10061) and a Linux-like value for ErrorCode and NativeErrorCode (111). Finally, let’s check macOS:
SocketErrorCode | ErrorCode | NativeErrorCode | |
Mono | 10061 | 10061 | 10061 |
.NET Core | 10061 | 61 | 61 |
Here, Mono is completely Windows-compatible again, but .NET Core returns 61 for ErrorCode and NativeErrorCode . In the IBM Knowledge Center, we can find a few more values for the connection refused error code from the Unix world (also known as ECONNREFUSED ):
- AIX: 79
- HP-UX: 239
- Solaris: 146
For a better understanding of what’s going on, let’s check out the source code of all the properties.
SocketErrorCode
These values correspond to the Windows Sockets Error Codes.
NativeErrorCode
In .NET Core, the native code is calculated in the constructor (see SocketException.cs#L20):
The Windows implementation of GetNativeErrorForSocketError is trivial (see SocketException.Windows.cs):
The Unix implementation is more complicated (see SocketException.Unix.cs):
TryGetNativeErrorForSocketError should convert SocketError to the native Unix error code. Unfortunately, there exists no unequivocal mapping between Windows and Unix error codes. As such, the .NET team decided to create a Dictionary that maps error codes in the best possible way (see SocketErrorPal.Unix.cs):
Once we have an instance of Interop.Error , we call interopErr.Info().RawErrno . The implementation of RawErrno can be found in Interop.Errors.cs:
Here we are jumping to the native function SystemNative_ConvertErrorPalToPlatform that maps Error to the native integer code that is defined in errno.h. You can get all the values using the errno util. Here is a typical output on Linux:
Note that errno may be not available by default in your Linux distro. For example, on Debian, you should call sudo apt-get install moreutils to get this utility. Here is a typical output on macOS:
Hooray! We’ve finished our fascinating journey into the internals of socket error codes. Now you know where .NET is getting the native error code for each SocketException from!
ErrorCode
Writing cross-platform socket error handling
There was a lot of work involved in tracking down the error code to check against, but in the end, our code is much more readable now. Adding to that, this method is now also completely cross-platform, and works correctly on any runtime.
Overview of the native error codes
We executed this program on Windows, Linux, and macOS. Here are the aggregated results:
Источник
Why do I receive «FLEXlm error: -15,570. System Error: 10038 Winsock: Specified socket is invalid» when I try to start MATLAB?
Direct link to this question
Direct link to this question
Accepted Answer
Direct link to this answer
Direct link to this answer
0 Comments
More Answers (0)
See Also
Categories
No tags entered yet.
Products
Find the treasures in MATLAB Central and discover how the community can help you!
An Error Occurred
Unable to complete the action because of changes made to the page. Reload the page to see its updated state.
Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .
You can also select a web site from the following list:
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
Americas
Europe
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- Deutsch
- English
- Français
- United Kingdom (English)
Asia Pacific
- Australia (English)
- India (English)
- New Zealand (English)
- 中国
- 简体中文 Chinese
- English
- 日本 Japanese (日本語)
- 한국 Korean (한국어)
Accelerating the pace of engineering and science
MathWorks is the leading developer of mathematical computing software for engineers and scientists.
Источник
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 badges464 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 TownsendSteve Townsend
53.2k9 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
Форум программистов Vingrad
Модераторы: feodorv |
Поиск: |
|
error 10038, в функции bind() |
Опции темы |
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;
}