Ошибка сокета 10038 citrix

"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:
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

  • 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

Problem

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

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

Symptom

image 2915

Citrix Receiver

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

Cause

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

Example: 

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

image 2920

Resolving The Problem

Upgrade to the latest version of the Citrix client.

Example:

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

Steps:

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

Related Information

Document Location

Worldwide

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

    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,0403 ]   [ 16 queries used ]   [ Generated: 12.02.23, 04:29 GMT ]  

                      Содержание

                      1. Ошибка socket error 10038
                      2. Why do I receive «FLEXlm error: -15,570. System Error: 10038 Winsock: Specified socket is invalid» when I try to start MATLAB?
                      3. Direct link to this question
                      4. Direct link to this question
                      5. Accepted Answer
                      6. Direct link to this answer
                      7. Direct link to this answer
                      8. More Answers (0)
                      9. See Also
                      10. Categories
                      11. Products
                      12. Community Treasure Hunt
                      13. How to Get Best Site Performance
                      14. Americas
                      15. Europe
                      16. Asia Pacific
                      17. How Socket Error Codes Depend on Runtime and Operating System
                      18. Digging into the problem
                      19. SocketErrorCode
                      20. NativeErrorCode
                      21. ErrorCode
                      22. Writing cross-platform socket error handling
                      23. Overview of the native error codes
                      24. Why do I receive «FLEXlm error: -15,570. System Error: 10038 Winsock: Specified socket is invalid» when I try to start MATLAB?
                      25. Direct link to this question
                      26. Direct link to this question
                      27. Accepted Answer
                      28. Direct link to this answer
                      29. Direct link to this answer
                      30. More Answers (0)
                      31. See Also
                      32. Categories
                      33. Products
                      34. Community Treasure Hunt
                      35. How to Get Best Site Performance
                      36. Americas
                      37. Europe
                      38. 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

                      SunilRai86's user avatar

                      SunilRai86SunilRai86

                      9706 gold badges16 silver badges26 bronze badges

                      0

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

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

                      answered Oct 16, 2010 at 8:34

                      Mitch Wheat's user avatar

                      Mitch WheatMitch Wheat

                      293k43 gold 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 Townsend's user avatar

                      Steve TownsendSteve Townsend

                      53.2k9 gold badges91 silver badges139 bronze badges

                      There may be two reasons for this:

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

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

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

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

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

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

                      answered Oct 16, 2010 at 10:21

                      valdo's user avatar

                      valdovaldo

                      12.5k2 gold badges35 silver badges65 bronze badges

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

                      answered Nov 9, 2017 at 18:17

                      Ted W's user avatar

                      Ted WTed W

                      2394 silver badges11 bronze badges

                      1


                      Форум программистов Vingrad

                      Модераторы: feodorv

                      Поиск:

                      Ответ в темуСоздание новой темы
                      Создание опроса
                      > error 10038, в функции bind() 

                      :(

                         

                      Опции темы

                      L0n3R4ng3r
                        Дата 8.4.2006, 20:11 (ссылка)
                      | (нет голосов)
                      Загрузка ... Загрузка …




                      Быстрая цитата

                      Цитата

                      Новичок

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

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

                      Вообщем обстоятельства и желания заставили меня учить работу с сокетами, почитав немого книжечку про создания сетевых приложения в Линуксе и порывшись в гугле и MSDN, я написал вот такое вот чудо:

                      Код

                      /*---------------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;
                          sockaddr_in addr_in;                
                          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_un.S_addr = htons(INADDR_LOOPBACK) ;
                          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-----------------------------------------*/

                      когда запучтил он мне выдало ошибку 10038, поюзал гугл нашел описание ошибки:

                      /*—————————————Описание ошибки————————————-*/
                      WSAENOTSOCK (10038) Socket operation on non-socket.

                      Berkeley description: An operation was attempted on something that is not a socket. The specified socket parameter refers to a file, not a socket.

                      WinSock description: Same as Berkeley. The socket input parameter is not a valid socket handle (either it never was valid, it’s a file handle (not a socket handle), or if it was a socket handle, it has been closed).

                      Detailed description:

                      select(): fails with WSAENOTSOCK if any socket in an fd_set is an invalid socket handle.

                      Developer suggestions: Did you close a socket inadvertently in one part of an application without keeping another part notified? Use socket state in an application and/or handle this error gracefully as a non-fatal error.

                      WinSock functions: Any function that takes a socket as an input parameter: accept(), bind(), closesocket(), connect(), getpeername(), getsockname(), getsockopt(), ioctl socket(), listen(), recv(), recvfrom(), select(), send(), sendto(), setsockopt(), shutdown(), FD_CONNECT

                      Additional functions: WSAAsyncSelect() should be in the list of functions (some applications might not register for or handle the FD_CONNECT message).
                      /*——————————————конец——————————————-*/

                      Короче сам я разобраться не смогsmile
                      Г.Ы. Буду благодарен за любую указаную помощь[code=cpp]

                      Это сообщение отредактировал(а) L0n3R4ng3r — 8.4.2006, 20:40

                      PM MAIL   Вверх
                      040375
                      Дата 9.4.2006, 19:59 (ссылка)
                      | (нет голосов)
                      Загрузка ... Загрузка …




                      Быстрая цитата

                      Цитата

                      Новичок

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

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

                      Ваша ошибка уважаемый в невнимательности и неправильном применении операции присваивания!
                      Рассмотрите хорошо строку
                      if (sd=socket(AF_INET, SOCK_STREAM , 0)>=0)
                      Как Вы думаете — что произойдёт в случае успешного завершения
                      socket? Вы полагаете что sd получит дескриптор сокета?
                      А как же приоритет? Ведь у булевых операций он выше — нежели у
                      оператора =. Вот Вам и ответ — sd всегда будет равен 1. т.к. при
                      конвертировании true — есть 1! А 1 в linux — это дескриптор вывода cin
                      если не ошибаюсь. В таких случаях в gcc чтобы страховаться от таких вещей
                      необходимо использовать опцию -pedantic или просто всегда стараться писать так
                      if ((sd=socket(AF_INET, SOCK_STREAM , 0))>=0).

                      PM MAIL   Вверх
                      L0n3R4ng3r
                      Дата 9.4.2006, 23:45 (ссылка)
                      | (нет голосов)
                      Загрузка ... Загрузка …




                      Быстрая цитата

                      Цитата

                      Новичок

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

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

                      Цитата
                      почитав немого книжечку про создания сетевых приложения в Линуксе

                      забыл дописать что программирую я в среде Windows на Visual C++6.0

                      …это так лирическое отступления…

                      исправил действительно sd было равно 1, сейчас ==1956, но существенно ничего не поменялось, ошибка таже самая что и была

                      Это сообщение отредактировал(а) L0n3R4ng3r — 9.4.2006, 23:45

                      PM MAIL   Вверх
                      040375
                      Дата 10.4.2006, 07:12 (ссылка)
                      | (нет голосов)
                      Загрузка ... Загрузка …




                      Быстрая цитата

                      Цитата

                      Новичок

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

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

                      Я понял по коду — что вы работаете в студио. После некоторых исправлений я скомпилировал в Visual C++ и успешно запустил Ваш код — ошибок там почти нет. Программа работает.
                      Не помню точно — что правил. Написать подробнее смогу часов через 10 к сожалению

                      PM MAIL   Вверх
                      040375
                      Дата 10.4.2006, 17:20 (ссылка)
                      | (нет голосов)
                      Загрузка ... Загрузка …




                      Быстрая цитата

                      Цитата

                      Новичок

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

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

                      Я не смог Вам сразу указать ошибку ещё одну — по той простой причине, что ввёл несколько
                      изменений сразу в Ваш код. В первую очередь конечно необходимо обращать внимаение на warning-и, которые говорят об изменеии или сокращении типов. Вот строки — которые я изменил в Вашем коде:

                      struct sockaddr_in addr_in_;
                      struct sockaddr asd;

                      — можно конечно и так как Вы написали — но в целях переносимости кода принято писать так.

                      А вот строка — из-за которой неверно задавался адрес сокета:
                      addr_in_.sin_addr.S_un.S_addr = htons(INADDR_LOOPBACK) ;

                      Заменил её на:
                      addr_in_.sin_addr.s_addr=inet_addr(«127.0.0.1»);
                      и всё заработало :-)

                      PM MAIL   Вверх
                      L0n3R4ng3r
                      Дата 10.4.2006, 17:57 (ссылка)
                      | (нет голосов)
                      Загрузка ... Загрузка …




                      Быстрая цитата

                      Цитата

                      Новичок

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

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

                      Вообщем может я что-то не то поменял но у меня не опять таже ошибка

                      Код

                      /*---------------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("127.0.0.1");    
                          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-----------------------------------------*/

                      PM MAIL   Вверх
                      040375
                      Дата 10.4.2006, 19:03 (ссылка)
                      | (нет голосов)
                      Загрузка ... Загрузка …




                      Быстрая цитата

                      Цитата

                      Новичок

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

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

                      Привожу весь Ваш код. Не касаясь тонкостесь и приёмов разработки сетевых приложений всё работает.
                      У меня запускается и ожидает соединения…
                      Возможно Вам просто нужно сделать rebild
                      Тот код, где инициализируется winsock в вашем варианте тоже верен,
                      порсто для меня так привычней.

                      Код

                      #include "Winsock2.h"
                      #include "Windows.h"
                      #include "stdio.h"
                      #include "string.h"
                      #pragma comment(lib, "ws2_32.lib")

                      int main()
                      {
                          int sd;
                          int bindw;
                          struct sockaddr_in addr_in;                
                          struct sockaddr asd;
                          WORD wVersionRequested;
                          WSADATA wsaData;
                          int err;

                           wVersionRequested = MAKEWORD( 2, 0 );
                          err = WSAStartup( wVersionRequested, &wsaData );
                          if ( err != 0 ) {
                              return -1;
                          }
                          ZeroMemory(&asd, sizeof(asd));
                          char buff[1024];
                          if ((sd=socket(AF_INET, SOCK_STREAM , 0))>0)        
                              printf("%d%sn", sd, "the socket is successfull create");        
                          else 
                          {
                              printf("Error bind %dn",WSAGetLastError());
                              closesocket(sd); 
                              WSACleanup();
                              return -2;
                          }
                          ZeroMemory(&addr_in, sizeof(addr_in));                
                          addr_in.sin_family=AF_INET;                            
                          addr_in.sin_port=htons(8025);//argv[2];
                          addr_in.sin_addr.s_addr=inet_addr("127.0.0.1");
                          if (bind(sd, (struct sockaddr *) &addr_in, sizeof(addr_in)))
                          {
                            printf("Error bind %dn",WSAGetLastError());
                            closesocket(sd);  
                            WSACleanup();
                            return -3;
                          }
                          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;
                      }

                      PM MAIL   Вверх
                      L0n3R4ng3r
                      Дата 10.4.2006, 19:44 (ссылка)
                      | (нет голосов)
                      Загрузка ... Загрузка …




                      Быстрая цитата

                      Цитата

                      Новичок

                      Профиль
                      Группа: Участник
                      Сообщений: 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)

                      PM MAIL   Вверх
                      040375
                        Дата 11.4.2006, 20:29 (ссылка)
                      | (нет голосов)
                      Загрузка ... Загрузка …




                      Быстрая цитата

                      Цитата

                      Новичок

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

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

                      Уважаемый, я вижу только одну проблему в Вашем коде. Прежде, чем садиться писать сетевые клиент-серверные приложения, советую обратить хоть какое то внимание на основы языка C.
                      Вы делаете ошибки, как впрочем и все мы, но Вы их не замечаете снова и снова.
                      Я обращу Ваше внимание только на некоторые, остальные найдёте сами.

                      ZeroMemory(&ip, sizeof(ip)); такое разрешено — но опять же — принято, что название массива
                      является и указателем на него — ZeroMemory(ip, sizeof(ip))

                      ZeroMemory(sock_in_, sizeof(sock_in_)); — здесь Вы обнуляете только первые 4 байта зачем-то динамически созданной структуры sockaddr_in

                      free(sock_in_) — если Вы создаёте структуру динамически с помощью new, то удалять следует с помощью delete, free освобождает память после malloc и т.п. …
                      Это что касается клиента.
                      Ну а в своём сервере Вы опять наступили на старые грабли:
                      (sd=socket(AF_INET, SOCK_STREAM , 0)>=0)….no comment
                      Дальше даже искать не стал.

                      Теперь что кается моего (Вашего поправленного) кода — как я уже сказал, я его запускал и он работает без ошибок (по крайней мере вышеназванных). Просто Вы скопировали его в редакторе
                      кода не оставив пустой последнюю строку или что-то в этом роде. Поставив курсор после последнего символа в коде нажмите Enter, чтобы редактор поставил там /n и EOF — такое случается в редакторах — я сам с этим сталкивался. И разберитесь с опциями компилятора.
                      Ну и наконец — возмите в руки книгу по С smile

                      PM MAIL   Вверх
                      L0n3R4ng3r
                      Дата 13.4.2006, 13:00 (ссылка)
                      | (нет голосов)
                      Загрузка ... Загрузка …




                      Быстрая цитата

                      Цитата

                      Новичок

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

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

                      спасибо за помощь, после этого поста все начало работатьsmile

                      PM MAIL   Вверх



















                      Ответ в темуСоздание новой темы
                      Создание опроса
                      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;
                      

                      }

                      Понравилась статья? Поделить с друзьями:
                    • Ошибка создания электронной подписи
                    • Ошибка создания шк весы штрих принт
                    • Ошибка создания кластера ошибка операции администрирования
                    • Ошибка создания информационной базы удаленный хост принудительно разорвал подключение
                    • Ошибка создания информационной базы ошибка операции администрирования сервер баз данных не обнаружен