Page 1 of 1

generic send recieve wrapper with wsa error check

Posted: Tue Sep 30, 2008 6:45 am
by idle
This is just a quick hack, though it took a few hours.
I've had a guts full of networking woes, so maybe this is on the right track.

Don't pay to much attention to the client and server example. it's basically ping ponging data back and forth.

Client

Code: Select all



Global *dat 
Global SID
Global Connection
Global bPause.b

XIncludeFile "SendRecieve.pbi"


Procedure NetClient(void.l)

Protected ct, ct1

While 1

   If Not Connection
      Connection = OpenNetworkConnection("127.0.0.1", 7500)
      If SetNoDelay(Connection.l,#False)
         MessageRequester("NetWork", "Set No Delay")
      EndIf      
   EndIf 
   
   EventType = NetworkClientEvent(Connection)   
   If EventType = #PB_NetworkEvent_Data
      
      LockMutex(RecMutex)
         mrx = Recieve(Connection)
      UnlockMutex(RecMutex)
      
      If mrx 
         AddGadgetItem(0, 0, Str(ct) + " Recieved " + Str(mrx))
         ct+1
         LockMutex(SendMutex)
           mtx = Send(Connection,*dat,Random(544288))
         UnlockMutex(SendMutex)
         If mtx 
           AddGadgetItem(0, 0, Str(ct1) + " Sent " + Str(mtx))
           ct1+1
         EndIf   
      Else 
         IsOK.l
         Debug lookupError(gLastError,IsOk,#False) 
         If IsOk 
           LockMutex(SendMutex)
             mtx = Send(Connection,*dat,666)
           UnlockMutex(SendMutex)
           If mtx 
             AddGadgetItem(0, 0, Str(ct1) + "Sent " + Str(mtx))
             ct1+1
           EndIf
         EndIf    
      EndIf    
   EndIf    

Delay(1)

Wend 

EndProcedure 

If InitNetwork() = 0
  MessageRequester("Error", "Can't initialize the network !", 0)
  End
EndIf

*dat = AllocateMemory(544288)

For a = 0 To 544288 -1
  PokeB(*dat+a,ct)
  ct + 1 
  If ct > 255 
  ct = 0 
  EndIf 
Next 

If OpenWindow(0,0,0,300,300,"",13565953)
    If CreateGadgetList(WindowID(0))
          TextGadget(5,5,0,290,20,"Client")     
          EditorGadget(0, 5, 25, 290, 220)
          ButtonGadget(1, 5, 250, 70, 20, "Send")
          ButtonGadget(2, 100, 250, 70, 20, "Pause")
          ButtonGadget(3, 225, 250, 70, 20, "&Quit")
                
     EndIf
             
            
         
    Repeat
    
        Event = WindowEvent()
    
        If Event = #PB_Event_Gadget
            
            Select EventGadget() 
            
            Case 1
               
               SID = CreateThread(@NetClient(),0) 
            Case 2 
               If IsThread(sid)
                If Not bpause 
                  PauseThread(sid)
                  bpause = #True 
                  SetGadgetText(2,"resume")
                Else 
                  ResumeThread(sid)
                  bpause = #False 
                  SetGadgetText(2,"pause")
                EndIf
               EndIf                       
            Case 3 
               If Connection
                 KillThread(sid)
                 FreeNetBuffer()
                 CloseNetworkConnection(Connection)
               EndIf 
               Event = #WM_CLOSE       
                                     
            EndSelect 
                             
        EndIf
        
              
    Delay(20)
    
    Until Event = #WM_CLOSE 
      
  EndIf
  
  If Connection 
    CloseNetworkConnection(Connection)
  EndIf   
  
  If IsThread(SID)
     KillThread(SID)
  EndIf 
  freeNetBuffer()   

  

Server

Code: Select all



Global *dat 
Global S1.l
Global SID.l
*dat = AllocateMemory(10000)

XIncludeFile "SendRecieve.pbi"


Procedure NetServer(void.l)

Protected ct, ct1

While 1 

      EventType = NetworkServerEvent() 
             
      Select eventType 
      
      Case #PB_NetworkEvent_Connect   
                  
          Connection = EventClient()
          LockMutex(SendMutex)
          mtx = send(Connection,*dat,Random(1000))   
          UnlockMutex(SendMutex)
          If mtx 
             AddGadgetItem(0, 0, Str(ct1) + " Sent " + Str(mtx))
             ct1+1
          Else 
             IsOK.l
             Debug lookupError(gLastError,IsOk,#False) 
             If IsOk 
               LockMutex(SendMutex)
               mtx = Send(Connection,*dat,666)
               UnlockMutex(SendMutex)
               If mtx 
                AddGadgetItem(0, 0, Str(ct1) + " Sent " + Str(mtx))
                ct1+1
               EndIf
             EndIf   
          EndIf 
          
      Case #PB_NetworkEvent_Data
          
          LockMutex(RecMutex)
          
            mrx = Recieve(Connection)
          
          UnlockMutex(RecMutex)
          
          If mrx 
              AddGadgetItem(0, 0, Str(ct) + " Recieved " + Str(mRx))
              ct+1
              LockMutex(SendMutex)
              mtx = Send(Connection,*dat,Random(1000))
              UnlockMutex(SendMutex)
              If mtx 
                AddGadgetItem(0, 0, Str(ct1) + " Sent " + Str(mtx))
                ct1+1
              EndIf   
          Else 
            IsOK.l
            Debug lookupError(gLastError,IsOk,#False ) 
            If IsOk 
              LockMutex(SendMutex)
              mtx = Send(Connection,*dat,666)
              UnlockMutex(SendMutex)
              If mtx 
                AddGadgetItem(0, 0, Str(ct1) + " Sent " + Str(mtx))
                ct1+1
              EndIf
            EndIf    
          EndIf    
                      
                    
      EndSelect       

  Delay(1)

Wend 


EndProcedure 


If InitNetwork() = 0
  MessageRequester("Error", "Can't initialize the network !", 0)
  End
EndIf

Port = 7500


S1 = CreateNetworkServer(#PB_Any, 7500)

  If OpenWindow(0,0,0,300,300,"",13565953)
    If CreateGadgetList(WindowID(0))
          TextGadget(5,5,0,290,20,"Server")        
          EditorGadget(0, 5, 25, 290, 220)
          ButtonGadget(1, 225, 250, 70, 20, "&Quit")
          
     EndIf
            
     SID = CreateThread(@NetServer(),0) 
     
    Repeat
    
        Event = WindowEvent()
    
        If Event = #PB_Event_Gadget
            
            Select EventGadget() 
                           
            Case 1 
               Event = #WM_CLOSE       
            
                      
            EndSelect 
                             
        EndIf
       
      
       
      
    Delay(20)
    
    Until Event = #WM_CLOSE 
      
  EndIf
  
  CloseNetworkServer(S1)
  
  If IsThread(SID)
     KillThread(SID)
  EndIf 
  
  FreeNetBuffer() 

wrapper

Code: Select all


;Author idle 30/9/2008   PB 4.20
 
;A Quick hack to wrap SendNetworkData and RecieveNetworkData, hopefully a no brainer to use, do whatever with it but please post improvements
;bug fixes, abuse or whatever.
;
;The Error Routine is unTested so no idea If it works as intended  
;Also as I don't know what half the errors are about,I don't know if they're recoverable or not, if they are then change the lpTimeOut. 


;bufferlen = 32767                             ;Internal Recive buffer length 
;NetBufferLen = 1024*1024                      ;Set to the max size you expect to recieve it will dynamically increase by bufferlen
;*NetDataBuffer = AllocateMemory(NetBufferLen) ;Global recievebuffer grows dynamically lock the recmutex to read from it 
;gLastErrorNum                                 ;Gets the last error - clear it after checking - used externally   
;gLastErrorStr.s                               ;Gets the last error - clear it after checking - used externally
;gRequest.b                                    ;Internal switch to enables or disable MessageRequester in LookUpError  
;gTimeout.l                                    ;Internal time out increment set to 250   

;Recieve(Connection.l)                         ;Returns the amount of data sent or zero if there was an error; 
;                                              ;Either LookupError to get a message requester - LookUpError(gLastErrorNum,@IsOk,#True) 
;                                              ;or use gLastErrorStr if you just want to write to debug or write to a logfile                          
;
;Send(Connection.l,*mData,Len.l)               ;Pass in a buffer address with it's lenght
                                               ;Returns the amount of Data sent Or zero If there was an error 
                                               ;Either use lookupError with gLastErrorNum for a messageRequester or  

;LookUpError(err.l,lpTimeOut,mRequest.b)       ;used internally and externally    
;                                              ;internally the function is called in the send and recieve functions 
                                               ;if you want to allert the user to an error set gRequest to #true     
;                                              ;call the routine if either send or recieve have returned 0 
; 
;
;SetSockOption(Socket.l,SockLevel.l,SockOption.l,Val.l)  ;use internally or externally 


;SetNoDelay(Connection.l,mbool.b)                        ;used externally to turn on and off the nagel sometimes useful    

;////////////////////////////////////////////////////////////////////////////////////////////
; some socket constants 

#IPPROTO_TCP = 6
#SOL_SOCKET = $FFFF             
#SO_KEEPALIVE = $8            ; send keepalive messages
#SO_LINGER = $80              ; linger on close if unsent data is present
#TCP_NODELAY   = $1           ; disable nagle algorithm 

;WSA Constants

#WSA_INVALID_HANDLE = 6
#WSA_NOT_ENOUGH_MEMORY = 8
#WSA_INVALID_PARAMETER = 87
#WSA_OPERATION_ABORTED = 995
#WSA_IO_INCOMPLETE = 996
#WSA_IO_PENDING = 997
#WSAEINTR = 10004
#WSAEBADF = 10009
#WSAEACCES = 10013
#WSAEFAULT = 10014
#WSAEINVAL = 10022
#WSAEMFILE = 10024
#WSAEWOULDBLOCK = 10035
#WSAEINPROGRESS = 10036
#WSAEALREADY = 10037
#WSAENOTSOCK = 10038
#WSAEDESTADDRREQ = 10039
#WSAEMSGSIZE = 10040
#WSAEPROTOTYPE = 10041
#WSAENOPROTOOPT = 10042
#WSAEPROTONOSUPPORT = 10043
#WSAESOCKTNOSUPPORT = 10044
#WSAEOPNOTSUPP = 10045
#WSAEPFNOSUPPORT = 10046
#WSAEAFNOSUPPORT = 10047
#WSAEADDRINUSE = 10048
#WSAEADDRNOTAVAIL = 10049
#WSAENETDOWN = 10050
#WSAENETUNREACH = 10051
#WSAENETRESET = 10052
#WSAECONNABORTED = 10053
#WSAECONNRESET = 10054
#WSAENOBUFS = 10055
#WSAEISCONN = 10056
#WSAENOTCONN = 10057
#WSAESHUTDOWN = 10058
#WSAETOOMANYREFS = 10059
#WSAETIMEDOUT = 10060
#WSAECONNREFUSED = 10061
#WSAELOOP = 10062
#WSAENAMETOOLONG = 10063
#WSAEHOSTDOWN = 10064
#WSAEHOSTUNREACH = 10065
#WSAENOTEMPTY = 10066
#WSAEPROCLIM = 10067
#WSAEUSERS = 10068
#WSAEDQUOT = 10069
#WSAESTALE = 10070
#WSAEREMOTE =10071
#WSASYSNOTREADY = 10091
#WSAVERNOTSUPPORTED = 10092
#WSANOTINITIALISED = 10093
#WSAEDISCON = 10101
#WSAENOMORE = 10102
#WSAECANCELLED = 10103
#WSAEINVALIDPROCTABLE = 10104
#WSAEINVALIDPROVIDER = 10105
#WSAEPROVIDERFAILEDINIT = 10106
#WSASYSCALLFAILURE = 10107
#WSASERVICE_NOT_FOUND = 10108
#WSATYPE_NOT_FOUND = 10109
#WSA_E_NO_MORE = 10110
#WSA_E_CANCELLED = 10111
#WSAEREFUSED = 10112
#WSAHOST_NOT_FOUND = 11001
#WSATRY_AGAIN = 11002
#WSANO_RECOVERY = 11003
#WSANO_DATA = 11004
#WSA_QOS_RECEIVERS = 11005
#WSA_QOS_SENDERS = 11006
#WSA_QOS_NO_SENDERS = 11007
#WSA_QOS_NO_RECEIVERS = 11008
#WSA_QOS_REQUEST_CONFIRMED = 11009
#WSA_QOS_ADMISSION_FAILURE = 11010
#WSA_QOS_POLICY_FAILURE = 11011
#WSA_QOS_BAD_STYLE = 11012
#WSA_QOS_BAD_OBJECT = 11013
#WSA_QOS_TRAFFIC_CTRL_ERROR = 11014
#WSA_QOS_GENERIC_ERROR = 11015
#WSA_QOS_ESERVICETYPE = 11016
#WSA_QOS_EFLOWSPEC = 11017
#WSA_QOS_EPROVSPECBUF = 11018
#WSA_QOS_EFILTERSTYLE = 11019
#WSA_QOS_EFILTERTYPE = 11020
#WSA_QOS_EFILTERCOUNT = 11021
#WSA_QOS_EOBJLENGTH = 11022
#WSA_QOS_EFLOWCOUNT = 11023
#WSA_QOS_EUNKOWNPSOBJ = 11024
#WSA_QOS_EPOLICYOBJ = 11025
#WSA_QOS_EFLOWDESC = 11026
#WSA_QOS_EPSFLOWSPEC = 11027
#WSA_QOS_EPSFILTERSPEC =11028
#WSA_QOS_ESDMODEOBJ = 11029
#WSA_QOS_ESHAPERATEOBJ = 11030
#WSA_QOS_RESERVED_PETYPE = 11031


;/////////////////////////////////////////////////////////////////////////////////////////////////
Global bufferlen = 32767                             ;default recieve buffer length 
Global NetBufferLen = 1024*1024                      ;set to the max size you expect to recieve
Global *NetDataBuffer = AllocateMemory(NetBufferLen) 
Global gLastErrorNum                                 ;gets set on last error 
Global gLastErrorStr.s                               ;gets set on error 
Global gTimeout.l = 250                              ;timeout increment on error 
Global RecMutex = CreateMutex()                      ;if your running it in threads  
Global SendMutex = CreateMutex()                      
Global gRequest.b = #False                           ;True to pop up a message requester (dorf idea really)  

;/////////////////////////////////////////////////////////////////////////////////////////////////

Declare Recieve(Connection.l)
Declare Send(Connection.l,*mdata,len.l)
Declare.s LookUpError(err.l,lpTimeOut.l,mRequest.b)
Declare SetSockOption(Socket.l,SockLevel.l,SockOption.l,Val.l)
Declare.b SetNoDelay(Connection.l,mbool.b)

;------------haven't actually tested the socket option stuff yet it appears to work------------

Procedure.b SetNoDelay(Connection.l,mBool.b)

  ProcedureReturn SetSockOption(Connection,#SOL_SOCKET,#TCP_NODELAY,mBool)

EndProcedure 

Procedure SetSockOption(Socket.l,SockLevel.l,SockOption.l,Val.l)
 
 mVal = Val
 
 If setsockopt_(Socket,SockLevel,SockOption,@mVal,Len) 
    ProcedureReturn mVal 
 Else 
    ProcedureReturn 0 
 EndIf

EndProcedure

;-----------------------------------------------------------------------------------------------

Procedure FreeNetBuffer()
 
 If *NetDataBuffer 
   FreeMemory(*NetDataBuffer)
   *NetDataBuffer = 0 
   FreeMutex(RecMutex)
   FreeMutex(SendMutex)
 EndIf 

EndProcedure 

Procedure Send(Connection.l,*mdata,len.l)

Protected *Out , Sz.l , Tx.l, Result.l, Dl.l,Timeout.l

*Out = AllocateMemory(len+4)
PokeL(*out,len+4)
CopyMemory(*mdata,*Out+4,len)
Sz = len + 4     
        
Tx = 0
        
  Repeat  
   
    Result = SendNetworkData(Connection ,*Out+Tx,Sz-Tx)
                   
    If Result <> -1 
      Tx = Tx + Result
      Dl=2
      Timeout = GetTickCount_() + gTimeout
    Else 
      err = WSAGetLastError_()
      LookupError(err,@Timeout,gRequest)
      If TimeOut > 0  
        dl=50
      EndIf 
    EndIf   
    Delay(dl)   
    
  Until Tx = Sz Or GetTickCount_() > Timeout 
   
    
  FreeMemory(*out)
  
  If TimeOut <> 0         
    ret = Tx  
  Else 
    ret = 0 
  EndIf   
  
  ProcedureReturn ret 
 
EndProcedure  

Procedure Recieve(Connection.l)
   
  Protected TotalBytesRead.l,BytesRead.l,*tB,Pk.l,Timeout,err.l,ret.l,dl.l
  
  
  *DataBuffer = AllocateMemory(bufferlen)
   
  TotalBytesRead = 0
  
  Repeat      ;
           
     BytesRead = ReceiveNetworkData(Connection, *DataBuffer,bufferlen) 
          
     If Pk = 0 And BytesRead > 4 
        Pk = PeekL(*DataBuffer) 
     EndIf 
           
     If BytesRead <> -1 
             
        If TotalBytesRead + BytesRead >= NetBufferLen 
           NetBufferLen + bufferlen ;increase the big buffer len  
           *tB = ReAllocateMemory(*NetDataBuffer,NetBufferLen)
           If *tB 
             *NetBigBuffer = *tB
           EndIf
           dl = 2  
        EndIf 
                       
        CopyMemory(*DataBuffer, *NetDataBuffer + TotalBytesRead, BytesRead)
        TotalBytesRead + BytesRead
        Timeout = GetTickCount_() + gTimeout  ;increment the time out here in case of WSAEWOULDBLOCK = 10035
           
     Else 
        err = WSAGetLastError_()  
        LookupError(err,@Timeout,gRequest)
        If Timeout > 0 
          dl = 50
        EndIf   
     EndIf 
           
     Delay(dl)  
                       
        
  Until TotalBytesRead = pk Or GetTickCount_() > Timeout 
        
  ;check the time out value if time out is zero we had an Error 
  If TimeOut <> 0         
     ret = TotalBytesRead  
  Else 
     ret = 0 
  EndIf   
     
  ProcedureReturn ret 
  
EndProcedure 


Procedure.s LookUpError(err.l,lpTimeout.l,mRequest.b)

retStr.s

Select err

  Case #WSA_INVALID_HANDLE

    retStr = "Specified event object handle is invalid."
    LpTimeOut = 0
    ;An application attempts To use an event object, but the specified handle is Not valid. Note that this error is returned by the operating system, so the error number may change in future releases of Windows.

  Case #WSA_NOT_ENOUGH_MEMORY 
	
    retStr = "Insufficient memory available."
    LpTimeOut = 0
    ;An application used a Windows Sockets function that directly maps To a Windows function. The Windows function is indicating a lack of required memory resources. Note that this error is returned by the operating system, so the error number may change in future releases of Windows.

  Case #WSA_INVALID_PARAMETER 
	
    retStr = "One Or more parameters are invalid."
    LpTimeOut = 0
    ; An application used a Windows Sockets function which directly maps To a Windows function. The Windows function is indicating a problem With one Or more parameters. Note that this error is returned by the operating system, so the error number may change in future releases of Windows.

  Case #WSA_OPERATION_ABORTED 
	

    retStr = "Overlapped operation aborted."
    LpTimeOut = 0
    ;An overlapped operation was canceled due To the closure of the socket, Or the execution of the SIO_FLUSH command in WSAIoctl. Note that this error is returned by the operating system, so the error number may change in future releases of Windows.

  Case #WSA_IO_INCOMPLETE 
	
    retStr = "Overlapped I/O event object Not in signaled state."
    LpTimeOut + gTimeout
    ;The application has tried To determine the status of an overlapped operation which is Not yet completed. Applications that use WSAGetOverlappedResult (With the fWait flag set To FALSE) in a polling mode To determine when an overlapped operation has completed, get this error code Until the operation is complete. Note that this error is returned by the operating system, so the error number may change in future releases of Windows.

  Case #WSA_IO_PENDING 
	
    retStr = "Overlapped operations will complete later."
    LpTimeOut + gTimeout
    ;The application has initiated an overlapped operation that cannot be completed immediately. A completion indication will be given later when the operation has been completed. Note that this error is returned by the operating system, so the error number may change in future releases of Windows.

  Case #WSAEINTR 
  
    retStr = "Interrupted function call"
    LpTimeOut + gTimeout 
    ;A blocking operation was interrupted by a call To WSACancelBlockingCall.

  Case #WSAEBADF 
	
    retStr = "File handle is Not valid."
    LpTimeOut = 0 
    ;The file handle supplied is Not valid.

  Case #WSAEACCES 
	
    retStr = "Permission denied."
    LpTimeOut =0 
   ;An attempt was made To access a socket in a way forbidden by its access permissions. An example is using a broadcast address For sendto without broadcast permission being set using setsockopt(SO_BROADCAST).
   ; Another possible reason For the WSAEACCES error is that when the bind function is called (on Windows NT 4 SP4 Or later), another application, service, Or kernel mode driver is bound To the same address With exclusive access. Such exclusive access is a new feature of Windows NT 4 SP4 And later, And is implemented by using the SO_EXCLUSIVEADDRUSE option.

  Case #WSAEFAULT 
	
    retStr = "Bad address."
    LpTimeOut = 0
    ;The system detected an invalid pointer address in attempting To use a pointer argument of a call. This error occurs If an application passes an invalid pointer value, Or If the length of the buffer is too small. For instance, If the length of an argument, which is a sockaddr Structure, is smaller than the SizeOf(sockaddr).

  Case #WSAEINVAL 
	
    retStr = "Invalid argument."
    LpTimeOut = 0
  ;Some invalid argument was supplied (For example, specifying an invalid level To the setsockopt function). In some instances, it also refers To the current state of the socket—For instance, calling accept on a socket that is Not listening.

  Case #WSAEMFILE 
	
    retStr = "Too many open files."
    LpTimeOut + gTimeout
    ;Too many open sockets. Each implementation may have a maximum number of socket handles available, either globally, per process, Or per thread.

  Case #WSAEWOULDBLOCK 
	
    retStr = "Resource temporarily unavailable."
    LpTimeOut + gTimeout
    ;This error is returned from operations on nonblocking sockets that cannot be completed immediately, For example recv when no Data is queued To be Read from the socket. It is a nonfatal error, And the operation should be retried later. It is normal For WSAEWOULDBLOCK To be reported As the result from calling connect on a nonblocking SOCK_STREAM socket, since some time must elapse For the connection To be established.

  Case #WSAEINPROGRESS 
	
    retStr = "Operation now in progress."
    LpTimeOut + gTimeout
    ; A blocking operation is currently executing. Windows Sockets only allows a single blocking operation—per- task Or thread—To be outstanding, And If any other function call is made (whether Or Not it references that Or any other socket) the function fails With the WSAEINPROGRESS error.

  Case #WSAEALREADY 
	
    retStr = "Operation already in progress."
    LpTimeOut + gTimeout 
    ;An operation was attempted on a nonblocking socket With an operation already in progress—that is, calling connect a second time on a nonblocking socket that is already connecting, Or canceling an asynchronous request (WSAAsyncGetXbyY) that has already been canceled Or completed.

  Case #WSAENOTSOCK 
	
    retStr = "Socket operation on nonsocket."
    LpTimeOut = 0
    ;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.

  Case #WSAEDESTADDRREQ 
	
    retStr = "Destination address required."
    LpTimeOut = 0
    ;A required address was omitted from an operation on a socket. For example, this error is returned If sendto is called With the remote address of ADDR_ANY.

  Case #WSAEMSGSIZE 
	
    retStr = "Message too long."
    LpTimeOut = 0
    ;A message sent on a datagram socket was larger than the internal message buffer Or some other network limit, Or the buffer used To receive a datagram was smaller than the datagram itself.

  Case #WSAEPROTOTYPE 
	
    retStr = "Protocol wrong type For socket."
    LpTimeOut = 0
    ;A protocol was specified in the socket function call that does Not support the semantics of the socket type requested. For example, the ARPA Internet UDP protocol cannot be specified With a socket type of SOCK_STREAM.

  Case #WSAENOPROTOOPT 
	
    retStr = "Bad protocol option."
    LpTimeOut = 0
    ;An unknown, invalid Or unsupported option Or level was specified in a getsockopt Or setsockopt call.

  Case #WSAEPROTONOSUPPORT 
	
    retStr = "Protocol Not supported."
    LpTimeOut = 0
    ;The requested protocol has Not been configured into the system, Or no implementation For it exists. For example, a socket call requests a SOCK_DGRAM socket, but specifies a stream protocol.

  Case #WSAESOCKTNOSUPPORT 
	
    retStr = "Socket type Not supported."
    LpTimeOut = 0
    ;The support For the specified socket type does Not exist in this address family. For example, the optional type SOCK_RAW might be selected in a socket call, And the implementation does Not support SOCK_RAW sockets at all.

  Case #WSAEOPNOTSUPP 
	
    retStr = "Operation Not supported."
    LpTimeOut = 0
    ;The attempted operation is Not supported For the type of object referenced. Usually this occurs when a socket descriptor To a socket that cannot support this operation is trying To accept a connection on a datagram socket.

  Case #WSAEPFNOSUPPORT 
	
    retStr = "Protocol family Not supported."
    LpTimeOut = 0
   ;The protocol family has Not been configured into the system Or no implementation For it exists. This message has a slightly different meaning from WSAEAFNOSUPPORT. However, it is interchangeable in most cases, And all Windows Sockets functions that Return one of these messages also specify WSAEAFNOSUPPORT.

  Case #WSAEAFNOSUPPORT 
	
    retStr = "Address family Not supported by protocol family."
    LpTimeOut = 0
    ;An address incompatible With the requested protocol was used. All sockets are created With an associated address family (that is, AF_INET For Internet Protocols) And a generic protocol type (that is, SOCK_STREAM). This error is returned If an incorrect protocol is explicitly requested in the socket call, Or If an address of the wrong family is used For a socket, For example, in sendto.

  Case #WSAEADDRINUSE 
	
    retStr = "Address already in use."
    LpTimeOut = 0
    ;Typically, only one usage of each socket address (protocol/IP address/port) is permitted. This error occurs If an application attempts To bind a socket To an IP address/port that has already been used For an existing socket, Or a socket that was Not closed properly, Or one that is still in the process of closing. For server applications that need To bind multiple sockets To the same port number, consider using setsockopt (SO_REUSEADDR). Client applications usually need Not call bind at all—connect chooses an unused port automatically. When bind is called With a wildcard address (involving ADDR_ANY), a WSAEADDRINUSE error could be delayed Until the specific address is committed. This could happen With a call To another function later, including connect, listen, WSAConnect, Or WSAJoinLeaf.

  Case #WSAEADDRNOTAVAIL 
	
    retStr = "Cannot assign requested address."
    LpTimeOut = 0
    ;The requested address is Not valid in its context. This normally results from an attempt To bind To an address that is Not valid For the local computer. This can also result from connect, sendto, WSAConnect, WSAJoinLeaf, Or WSASendTo when the remote address Or port is Not valid For a remote computer (For example, address Or port 0).

  Case #WSAENETDOWN 
	
    retStr = "Network is down."
    LpTimeOut = 0
    ;A socket operation encountered a dead network. This could indicate a serious failure of the network system (that is, the protocol stack that the Windows Sockets DLL runs over), the network Interface, Or the local network itself.

  Case #WSAENETUNREACH 
	
    retStr = "Network is unreachable."
    LpTimeOut = 0
    ;A socket operation was attempted To an unreachable network. This usually means the local software knows no route To reach the remote host.

  Case #WSAENETRESET 
	
    retStr = "Network dropped connection on reset."
    LpTimeOut = 0
    ;The connection has been broken due To keep-alive activity detecting a failure While the operation was in progress. It can also be returned by setsockopt If an attempt is made To set SO_KEEPALIVE on a connection that has already failed.

  Case #WSAECONNABORTED 

    retStr = "Software caused connection abort."
    LpTimeOut = 0
    ;An established connection was aborted by the software in your host computer, possibly due To a Data transmission time-out Or protocol error.

  Case #WSAECONNRESET 
	
    retStr = "Connection reset by peer."
    LpTimeOut = 0
    ;An existing connection was forcibly closed by the remote host. This normally results If the peer application on the remote host is suddenly stopped, the host is rebooted, the host Or remote network Interface is disabled, Or the remote host uses a hard close (see setsockopt For more information on the SO_LINGER option on the remote socket). This error may also result If a connection was broken due To keep-alive activity detecting a failure While one Or more operations are in progress. Operations that were in progress fail With WSAENETRESET. Subsequent operations fail With WSAECONNRESET.

  Case #WSAENOBUFS 
	
    retStr = "No buffer space available."
    LpTimeOut = 0
    ;An operation on a socket could Not be performed because the system lacked sufficient buffer space Or because a queue was full.

  Case #WSAEISCONN 
	
    retStr = "Socket is already connected."
    LpTimeOut = 0
    ;A connect request was made on an already-connected socket. Some implementations also Return this error If sendto is called on a connected SOCK_DGRAM socket (For SOCK_STREAM sockets, the To parameter in sendto is ignored) although other implementations treat this As a legal occurrence.

  Case #WSAENOTCONN 
	
    retStr = "Socket is Not connected."
    LpTimeOut = 0 
    ;A request To send Or receive Data was disallowed because the socket is Not connected And (when sending on a datagram socket using sendto) no address was supplied. Any other type of operation might also Return this error—For example, setsockopt setting SO_KEEPALIVE If the connection has been reset.

  Case #WSAESHUTDOWN 
	
    retStr = "Cannot send after socket shutdown."
    LpTimeOut = 0
    ;A request To send Or receive Data was disallowed because the socket had already been shut down in that direction With a previous shutdown call. By calling shutdown a partial close of a socket is requested, which is a signal that sending Or receiving, Or both have been discontinued.

  Case #WSAETOOMANYREFS 
	
    retStr = "Too many references."
    LpTimeOut = 0
    ;Too many references To some kernel object.

  Case #WSAETIMEDOUT 
	
    retStr = "Connection timed out."
    LpTimeOut = 0
    ;A connection attempt failed because the connected party did Not properly respond after a period of time, Or the established connection failed because the connected host has failed To respond.

  Case #WSAECONNREFUSED 
	
    retStr = "Connection refused."
    LpTimeOut = 0
    ;No connection could be made because the target computer actively refused it. This usually results from trying To connect To a service that is inactive on the foreign host—that is, one With no server application running.

  Case #WSAELOOP 
	
    retStr = "Cannot translate name."
    LpTimeOut = 0

  Case #WSAENAMETOOLONG 
	
    retStr = "Name too long."
    LpTimeOut = 0
    ;A name component Or a name was too long.

  Case #WSAEHOSTDOWN 

    retStr = "Host is down."
    LpTimeOut = 0
    ;A socket operation failed because the destination host is down. A socket operation encountered a dead host. Networking activity on the local host has Not been initiated. These conditions are more likely To be indicated by the error WSAETIMEDOUT.

  Case #WSAEHOSTUNREACH 
	
    retStr = "No route To host."
    LpTimeOut = 0
    ;A socket operation was attempted To an unreachable host. See WSAENETUNREACH.

  Case #WSAENOTEMPTY 	

    retStr = "Directory Not empty."
    LpTimeOut = 0
    ;Cannot remove a directory that is Not empty.

  Case #WSAEPROCLIM 
	
    retStr = "Too many processes."
    LpTimeOut = 0
    ;A Windows Sockets implementation may have a limit on the number of applications that can use it simultaneously.WSAStartup may fail With this error If the limit has been reached.

  Case #WSAEUSERS 
	
    retStr = "User quota exceeded."
    LpTimeOut = 0
    ;Ran out of user quota.

  Case #WSAEDQUOT 
	
    retStr = "Disk quota exceeded."
    LpTimeOut = 0
    ;Ran out of disk quota.

  Case #WSAESTALE 
	
    retStr = "Stale file handle reference."
    LpTimeOut = 0
    ;The file handle reference is no longer available.

  Case #WSAEREMOTE 
	
      retStr = "Item is remote."
      LpTimeOut = 0
    ;The item is Not available locally.

  Case #WSASYSNOTREADY 
	
    retStr = "Network subsystem is unavailable."
    LpTimeOut = 0
    ;This error is returned by WSAStartup If the Windows Sockets implementation cannot function at this time because the underlying system it uses To provide network services is currently unavailable. Users should check:

;   * That the appropriate Windows Sockets DLL file is in the current path.
;    * That they are Not trying To use more than one Windows Sockets implementation simultaneously. If there is more than one Winsock DLL on your system, be sure the first one in the path is appropriate For the network subsystem currently loaded.
;    * The Windows Sockets implementation documentation To be sure all necessary components are currently installed And configured correctly.

  Case #WSAVERNOTSUPPORTED 
	
    retStr = "Winsock.dll version out of range."
    LpTimeOut = 0
  ;The current Windows Sockets implementation does Not support the Windows Sockets specification version requested by the application. Check that no old Windows Sockets DLL files are being accessed.

  Case #WSANOTINITIALISED 
	
    retStr = "Successful WSAStartup Not yet performed."
    LpTimeOut = 0
    ;Either the application has Not called WSAStartup Or WSAStartup failed. The application may be accessing a socket that the current active task does Not own (that is, trying To share a socket between tasks), Or WSACleanup has been called too many times.

  Case #WSAEDISCON 
	
      retStr = "Graceful shutdown in progress."
      LpTimeOut = 0
      ;Returned by WSARecv And WSARecvFrom To indicate that the remote party has initiated a graceful shutdown sequence.

  Case #WSAENOMORE 

      retStr = "No more results."
      LpTimeOut = 0
    ;No more results can be returned by the WSALookupServiceNext function.

  Case #WSAECANCELLED 
	
      retStr = "Call has been canceled."
      LpTimeOut = 0
        ;A call To the WSALookupServiceEnd function was made While this call was still processing. The call has been canceled.

  Case #WSAEINVALIDPROCTABLE 

    retStr = "Procedure call table is invalid."
    LpTimeOut = 0 
    ;The service provider Procedure call table is invalid. A service provider returned a bogus Procedure table To Ws2_32.dll. This is usually caused by one Or more of the function pointers being NULL.

  Case #WSAEINVALIDPROVIDER 

    retStr = "Service provider is invalid."
    LpTimeOut = 0
    ;The requested service provider is invalid. This error is returned by the WSCGetProviderInfo And WSCGetProviderInfo32 functions If the protocol entry specified could Not be found. This error is also returned If the service provider returned a version number other than 2.0.

  Case #WSAEPROVIDERFAILEDINIT 

    retStr = "Service provider failed To initialize."
    LpTimeOut = 0
    ;The requested service provider could Not be loaded Or initialized. This error is returned If either a service provider's DLL could not be loaded (LoadLibrary failed) or the provider's WSPStartup Or NSPStartup function failed.

  Case #WSASYSCALLFAILURE 
	
      retStr = "System call failure."
      LpTimeOut = 0
      ;A system call that should never fail has failed. This is a generic error code, returned under various conditions.

      ;Returned when a system call that should never fail does fail. For example, If a call To WaitForMultipleEvents fails Or one of the registry functions fails trying To manipulate the protocol/namespace catalogs.

      ;Returned when a provider does Not Return SUCCESS And does Not provide an extended error code. Can indicate a service provider implementation error.

  Case #WSASERVICE_NOT_FOUND 
	
      retStr = "Service Not found."
      LpTimeOut = 0
    ;No such service is known. The service cannot be found in the specified name space.

  Case #WSATYPE_NOT_FOUND 
	
      retStr = "Class type Not found."
      LpTimeOut = 0
    ;The specified class was Not found.

  Case #WSA_E_NO_MORE 

      retStr = "No more results."
      LpTimeOut = 0
      ;No more results can be returned by the WSALookupServiceNext function.

  Case #WSA_E_CANCELLED 

    retStr = "Call was canceled."
     LpTimeOut = 0
    ;A call To the WSALookupServiceEnd function was made While this call was still processing. The call has been canceled.

  Case #WSAEREFUSED 
	
    retStr = "Database query was refused."
    LpTimeOut = 0 
    ;A database query failed because it was actively refused.

  Case #WSAHOST_NOT_FOUND 
	
     retStr = "Host Not found."
     LpTimeOut = 0
    ;No such host is known. The name is Not an official host name Or alias, Or it cannot be found in the database(s) being queried. This error may also be returned For protocol And service queries, And means that the specified name could Not be found in the relevant database.

  Case #WSATRY_AGAIN 
	
    retStr = "Nonauthoritative host Not found."
    LpTimeOut = 0
    ;This is usually a temporary error during host name resolution And means that the local server did Not receive a response from an authoritative server. A retry at some time later may be successful.

  Case #WSANO_RECOVERY 
	
      retStr = "This is a nonrecoverable error."
      LpTimeOut = 0
      ;This indicates that some sort of nonrecoverable error occurred during a database lookup. This may be because the database files (For example, BSD-compatible HOSTS, SERVICES, Or PROTOCOLS files) could Not be found, Or a DNS request was returned by the server With a severe error.

  Case #WSANO_DATA 
	
      retStr = "Valid name, no Data record of requested type."
      LpTimeOut = 0
      ;The requested name is valid And was found in the database, but it does Not have the correct associated Data being resolved For. The usual example For this is a host name-To-address translation attempt (using gethostbyname Or WSAAsyncGetHostByName) which uses the DNS (Domain Name Server). An MX record is returned but no A record—indicating the host itself exists, but is Not directly reachable.

  Case #WSA_QOS_RECEIVERS 
	
      retStr = "QOS receivers."
      
      ;At least one QOS reserve has arrived.

  Case #WSA_QOS_SENDERS 
	
      retStr = "QOS senders."

      ;At least one QOS send path has arrived.

  Case #WSA_QOS_NO_SENDERS 
	
      retStr = "No QOS senders."

      ;There are no QOS senders.

  Case #WSA_QOS_NO_RECEIVERS 
	
      retStr = "QOS no receivers."

      ;There are no QOS receivers.

  Case #WSA_QOS_REQUEST_CONFIRMED 
	
      retStr = "QOS request confirmed."

      ;The QOS reserve request has been confirmed.

  Case #WSA_QOS_ADMISSION_FAILURE 
	
      retStr = "QOS admission error."
      LpTimeOut = 0
      ;A QOS error occurred due To lack of resources.

  Case #WSA_QOS_POLICY_FAILURE 
	
      retStr = "QOS policy failure."
      LpTimeOut = 0
      ;The QOS request was rejected because the policy system couldn't allocate the requested resource within the existing policy.

  Case #WSA_QOS_BAD_STYLE 
	
      retStr = "QOS bad style."
      LpTimeOut = 0
      ;An unknown Or conflicting QOS style was encountered.

  Case #WSA_QOS_BAD_OBJECT 
	
      retStr = "QOS bad object."
      LpTimeOut = 0
      ;A problem was encountered With some part of the filterspec Or the provider-specific buffer in general.

  Case #WSA_QOS_TRAFFIC_CTRL_ERROR 
	
      retStr = "QOS traffic control error."
      LpTimeOut = 0
      ;An error With the underlying traffic control (TC) API As the generic QOS request was converted For local enforcement by the TC API. This could be due To an out of memory error Or To an internal QOS provider error.

  Case #WSA_QOS_GENERIC_ERROR 
	
      retStr = "QOS generic error."
      LpTimeOut = 0 
      ;A general QOS error.

  Case #WSA_QOS_ESERVICETYPE 
	
      retStr = "QOS service type error."
      LpTimeOut = 0 
      ;An invalid Or unrecognized service type was found in the QOS flowspec.

  Case #WSA_QOS_EFLOWSPEC 
	
      retStr = "QOS flowspec error."
      LpTimeOut = 0
      ;An invalid Or inconsistent flowspec was found in the QOS Structure.

  Case #WSA_QOS_EPROVSPECBUF 
	
      retStr = "Invalid QOS provider buffer."
      LpTimeOut = 0
      ; An invalid QOS provider-specific buffer.

  Case #WSA_QOS_EFILTERSTYLE 
	
      retStr = "Invalid QOS filter style."
      LpTimeOut = 0
      ;An invalid QOS filter style was used.

  Case #WSA_QOS_EFILTERTYPE 
	
    retStr = "Invalid QOS filter type."
    LpTimeOut = 0
    ;An invalid QOS filter type was used.

  Case #WSA_QOS_EFILTERCOUNT 

      retStr = "Incorrect QOS filter count."
      LpTimeOut = 0
      ;An incorrect number of QOS FILTERSPECs were specified in the FLOWDESCRIPTOR.

  Case #WSA_QOS_EOBJLENGTH 
    
      retStr = "Invalid QOS object length."
      LpTimeOut = 0
      ;An object With an invalid ObjectLength field was specified in the QOS provider-specific buffer.

  Case #WSA_QOS_EFLOWCOUNT 

      retStr = "Incorrect QOS flow count."
      LpTimeOut = 0
      ;An incorrect number of flow descriptors was specified in the QOS Structure.

  Case #WSA_QOS_EUNKOWNPSOBJ 

      retStr = "Unrecognized QOS object."
      LpTimeOut = 0
      ;An unrecognized object was found in the QOS provider-specific buffer.

  Case #WSA_QOS_EPOLICYOBJ 

      retStr = "Invalid QOS policy object."
      LpTimeOut = 0
      ;An invalid policy object was found in the QOS provider-specific buffer.

  Case #WSA_QOS_EFLOWDESC 
	
      retStr = "Invalid QOS flow descriptor."
      LpTimeOut = 0
      ;An invalid QOS flow descriptor was found in the flow descriptor list.

  Case #WSA_QOS_EPSFLOWSPEC 

      retStr = "Invalid QOS provider-specific flowspec."
      LpTimeOut = 0
      ;An invalid Or inconsistent flowspec was found in the QOS provider-specific buffer.

  Case #WSA_QOS_EPSFILTERSPEC 

      retStr = "Invalid QOS provider-specific filterspec."
      LpTimeOut = 0
      ;An invalid FILTERSPEC was found in the QOS provider-specific buffer.

  Case #WSA_QOS_ESDMODEOBJ 

      retStr = "Invalid QOS shape discard mode object."
      LpTimeOut = 0
      ;An invalid shape discard mode object was found in the QOS provider-specific buffer.

  Case #WSA_QOS_ESHAPERATEOBJ 

      retStr = "Invalid QOS shaping rate object."
      LpTimeOut = 0
      ;An invalid shaping rate object was found in the QOS provider-specific buffer.

  Case #WSA_QOS_RESERVED_PETYPE 
	
    retStr = "Reserved policy QOS element type."
    LpTimeOut = 0
    ;A reserved policy element was found in the QOS provider-specific buffer.
  
    
  EndSelect 
  
  gLastErrorNum = err
  gLastErrorStr = retStr
  
  If mRequest 
      MessageRequester("NetWork Error", retStr,#PB_MessageRequester_Ok)  
  EndIf 
  
  ProcedureReturn retStr


EndProcedure