Jump to content
j0kky

Winsock UDF

Recommended Posts

TurionAltec

On the UDF, one feature I like is immediately knowing the IP/port of an incoming client. I've been looking at implementing application level IP filtering. It also looks like TCPRecv will actually respond correctly if the connection is closed. As I recall the built in TCPRecv has been broken in this regard for years.

 

 

TCP Keepalive

I've run into problems where idle connections are dropped from stateful firewalls. Usually after an hour or so, or they drop off a list as being unused (if there's a maximum number of connections). The socket will still appear to be active on both sides, but if the server tries to send data it will fail and close the connection on that side. The client will still think it's connected until it tries to send data. As well if the server PC were to crash, the client would never know. Ideally there you should have an application level Keepalive, for example Telnet command 0xFFF1, sent from both sides periodically to determine if the link is down, and to keep the connection active in any intermediate routers and firewalls.

 

The TCP stack has an "SO_KEEPALIVE" option. An example of an application that can use this is the "Connection" configuration for PuTTY.  The time for no activity before firing a keepalive is set by the registry entry "KeepAliveTime". The default is 2 hours which is too long, 300,000ms (5 minutes)  is a good recommendation. I wouldn't want to venture below 1 minute. These keepalives should keep your connection active in any firewalls, and will alert your application if the connection is broken. This option is off by default and must be enabled on a per connection basis.

 

Here's a "_TCPKeepAlive()" function that's a good fit for this UDF. @j0kky's use of Winsock API let me bluff my way around DllCall.

; #FUNCTION# ====================================================================================================================
; Name...........: _TCPKeepAlive
; Description ...: Set SO_KEEPALIVE Socket Option to enable stack level keepalive
; Syntax.........: _TCPKeepAlive($iMainsocket)
; Parameters ....: $iMainsocket - The array as returned by _TCPAccept
;                                 or the connected socket identifier (SocketID) as returned by _TCPListen and _TCPConnect.
; Return values .: On success it returns:
;                  |0  - Success.
;                  On failure it returns -1 and sets @error to non zero:
;                  |-1 - internal error
;                  |-2 - missing DLL (Ws2_32.dll)
;                  |-3 - undefined error
;                  |Any Windows Socket Error Code retrieved by WSAGetLastError
; Author ........: TurionAltec
; Modified ......: 0.0.1
; Remarks .......: KeepAlive will send a keepalive packet without sending any data.
;                  Some Firewalls may drop idle connections which can cause problems if a connection is quiet for an hour+
;                  Can also be used to detect if the other end of a connection was dropped (computer abruptly powered off)
;
;                  Delay with no traffic before sending packet set globally from registry key:
;                  HKLM\System\CurrentControlSet\Services\Tcpip\Parameters\KeepAliveTime
;                  Default is 7200000 (1 hour) Recommended is 300000 (5 minutes)
;
;                  "On Windows Vista and later, the SO_KEEPALIVE socket option can only be set using the setsockopt function
;                  when the socket is in a well-known state not a transitional state."
;
; Links .........: SO_KEEPALIVE:            https://msdn.microsoft.com/en-us/library/windows/desktop/ee470551(v=vs.85).aspx
;                  setsockopt function:     https://msdn.microsoft.com/en-us/library/windows/desktop/ms740476(v=vs.85).aspx
;                  KeepAliveTime Reg Entry: https://technet.microsoft.com/en-us/library/dd349797(v=ws.10).aspx#BKMK_2
; ===============================================================================================================================
Func _TCPKeepAlive($iMainsocket)
    If IsArray($iMainsocket) And (UBound($iMainsocket, 0) = 1) And (UBound($iMainsocket) > 0) Then $iMainsocket = $iMainsocket[0]
    Local $SOL_SOCKET = 0xffff
    Local $SO_KEEPALIVE = 0x0008
    Local $hWs2 = DllOpen("Ws2_32.dll")
    If @error Then Return SetError(-2, 0, -1) ;missing DLL
    Local $bError = 0, $nCode = 0, $nExtended = 0

    If Not $bError Then
        $aRet = DllCall($hWs2, "int", "setsockopt", "uint", $iMainsocket, "int", $SOL_SOCKET, "int", $SO_KEEPALIVE, "int*", 1, "int", 4)
        ;MSDN calls for "char*" not "int*", but DLLCall returns @Error=1 for char
        If @error Then
            $bError = -1
        ElseIf $aRet[0] <> 0 Then ;SOCKET_ERROR
            $bError = 1
        EndIf
    EndIf
    If $bError < 0 Then
        $nCode = -1 ;internal error
        $nReturn = -1 ;failure

    ElseIf $bError > 0 Then
        If Not $nCode Then
            $aRet = DllCall($hWs2, "int", "WSAGetLastError")
            If @error Then
                $nCode = -1
            Else
                $nCode = $aRet[0]
            EndIf
            If $nCode = 0 Then $nCode = -3 ;undefined error
        EndIf
        If $nCode = -10 Then $nCode = 0
        $nReturn = -1

    Else
        $nReturn = $aRet
    EndIf
    DllClose($hWs2)
    Return SetError($nCode, 0, $nReturn)

EndFunc   ;==>_TCPKeepAlive

KeepAliveTime.reg:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters]
"KeepAliveTime"=dword:000493e0

;Hex 493e0 = Decimal 300000
;300,000 ms = 5 minutes

I call _TCPKeepAlive() after _TCPAccept(), or _TCPConnect() return a good socket identifier. Note that MSDN says the sockets must not be in a transitional state…

I found the included example scripts a little wonky, but below is a Wireshark Trace. I had sent the KeepAliveTime to 10 seconds for demonstration on the server, 10.0.0.2.

r1h5k0.png

 

"A TCP keep-alive packet is simply an ACK with the sequence number set to one less than the current sequence number for the connection. A host receiving one of these ACKs will respond with an ACK for the current sequence number."

Now if only I can figure out how to set keepalive on sockets owned by another application!
 

Edited by TurionAltec

Share this post


Link to post
Share on other sites
Lecdev

could this be extended to utilize the setsockopt winsock function to add to multicast groups and enable sending multicast packets? I'd be very interested in that.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Similar Content

    • Gowrisankar
      By Gowrisankar
      Dear members, 
      I am working on a project where, emails from outlook are to be read and moved to various folders within the mailbox, based on the content of the emails.
      I used the below code for moving mails. It works fine when I run it against individual mail ids. But when I run it on Shared mailbox, the mails are not moved to respective folders.
      _OL_ItemMove($oOutlook, $sEntryId, Default, $sDestinationFolder) The value of $sEntryId is saved in an excel report initially. The current process reads the $sEntryId from the excel and passes it to "_OL_ItemMove" statement.
      Requesting the guidance of the forum members in this issue.
    • FrancescoDiMuro
      By FrancescoDiMuro
      Good evening everyone
      I am working with Word UDF ( thanks @water! ), and, especially, with the function _Word_DocFindReplace().
      The replace does work everywhere in the document, but, it does not work in Headers or Footers.
      Am I missing something or am I forced to use the code below?
      I have already looked in the Help file ( about _Word_DocFindReplace() ), but there are no mentions about replace text in Headers/Footers.
      Sub FindAndReplaceFirstStoryOfEachType() Dim rngStory As Range For Each rngStory In ActiveDocument.StoryRanges With rngStory.Find .Text = "find text" .Replacement.Text = "I'm found .Wrap = wdFindContinue .Execute Replace:=wdReplaceAll End With Next rngStory End Sub Thanks everyone in advance


      Best Regards.
    • ScriptJunky
      By ScriptJunky
      I noticed a lack of a constants file for _WinAPI_GetSystemMetrics() so I made this for anyone who wants to add it to their library. Enjoy!  (file attached below)
      #include-once ; #INDEX# ======================================================================================================================= ; Title .........: WinAPI GetSystemMetrics Constants ; AutoIt Version : 3.3.14.5 ; Language ......: English ; Description ...: Constants for _WinAPI_GetSystemMetrics(). ; Author(s) .....: ScriptJunky ; =============================================================================================================================== ; #CONSTANTS# =================================================================================================================== ; _WinAPI_GetSystemMetrics() Global Const $ARRANGE = 56 Global Const $CLEANBOOT = 67 Global Const $CMONITORS = 80 Global Const $CMOUSEBUTTONS = 43 Global Const $CONVERTIBLESLATEMODE = 0x2003 Global Const $CXBORDER = 5 Global Const $CXCURSOR = 13 Global Const $CXDLGFRAME = 7 Global Const $CXDOUBLECLK = 36 Global Const $CXDRAG = 68 Global Const $CXEDGE = 45 Global Const $CXFIXEDFRAME = 7 Global Const $CXFOCUSBORDER = 83 Global Const $CXFRAME = 32 Global Const $CXFULLSCREEN = 16 Global Const $CXHSCROLL = 21 Global Const $CXHTHUMB = 10 Global Const $CXICON = 11 Global Const $CXICONSPACING = 38 Global Const $CXMAXIMIZED = 61 Global Const $CXMAXTRACK = 59 Global Const $CXMENUCHECK = 71 Global Const $CXMENUSIZE = 54 Global Const $CXMIN = 28 Global Const $CXMINIMIZED = 57 Global Const $CXMINSPACING = 47 Global Const $CXMINTRACK = 34 Global Const $CXPADDEDBORDER = 92 Global Const $CXSCREEN = 0 Global Const $CXSIZE = 30 Global Const $CXSIZEFRAME = 32 Global Const $CXSMICON = 49 Global Const $CXSMSIZE = 52 Global Const $CXVIRTUALSCREEN = 78 Global Const $CXVSCROLL = 2 Global Const $CYBORDER = 6 Global Const $CYCAPTION = 4 Global Const $CYCURSOR = 14 Global Const $CYDLGFRAME = 8 Global Const $CYDOUBLECLK = 37 Global Const $CYDRAG = 69 Global Const $CYEDGE = 46 Global Const $CYFIXEDFRAME = 8 Global Const $CYFOCUSBORDER = 84 Global Const $CYFRAME = 33 Global Const $CYFULLSCREEN = 17 Global Const $CYHSCROLL = 3 Global Const $CYICON = 12 Global Const $CYICONSPACING = 39 Global Const $CYKANJIWINDOW = 18 Global Const $CYMAXIMIZED = 62 Global Const $CYMAXTRACK = 60 Global Const $CYMENU = 15 Global Const $CYMENUCHECK = 72 Global Const $CYMENUSIZE = 55 Global Const $CYMIN = 29 Global Const $CYMINIMIZED = 58 Global Const $CYMINSPACING = 48 Global Const $CYMINTRACK = 35 Global Const $CYSCREEN = 1 Global Const $CYSIZE = 31 Global Const $CYSIZEFRAME = 33 Global Const $CYSMCAPTION = 51 Global Const $CYSMICON = 50 Global Const $CYSMSIZE = 53 Global Const $CYVIRTUALSCREEN = 79 Global Const $CYVSCROLL = 20 Global Const $CYVTHUMB = 9 Global Const $DBCSENABLED = 42 Global Const $DEBUG = 22 Global Const $DIGITIZER = 94 Global Const $IMMENABLED = 82 Global Const $MAXIMUMTOUCHES = 95 Global Const $MEDIACENTER = 87 Global Const $MENUDROPALIGNMENT = 40 Global Const $MIDEASTENABLED = 74 Global Const $MOUSEPRESENT = 19 Global Const $MOUSEHORIZONTALWHEELPRESENT = 91 Global Const $MOUSEWHEELPRESENT = 75 Global Const $NETWORK = 63 Global Const $PENWINDOWS = 41 Global Const $REMOTECONTROL = 0x2001 Global Const $REMOTESESSION = 0x1000 Global Const $SAMEDISPLAYFORMAT = 81 Global Const $SECURE = 44 Global Const $SERVERR = 289 Global Const $SHOWSOUNDS = 70 Global Const $SHUTTINGDOWN = 0x2000 Global Const $SLOWMACHINE = 73 Global Const $STARTER = 88 Global Const $SWAPBUTTON = 23 Global Const $TABLETPC = 86 Global Const $XVIRTUALSCREEN = 76 Global Const $YVIRTUALSCREEN = 77  
      WinAPISystemMetricsConstants.au3
    • rcmaehl
      By rcmaehl
      A UDF with Extended Functions for Window Management
       
      Notes:
      Fixes WinGetClassList's barbaric returning of a @LF separated string instead of an array.
       
      Potential Uses:
      Automating applications that change their controls' handles/classes on each launch (e.g. half of Cisco's programs)
       
      Functions:
      _WinGetClassList
      _WinGetClassNNList
      _WindowGetHandleList
      _WindowGetHandleListFromPos
       
      Download: 
      WindowEx.zip  (v0.4)
       
      Changelog:
      10/04/2016 (v0.4): _WinGetClassNNList Fixed : Not Returning an Index when using $2D_ARRAY _WinGetClassNNList Fixed : Not Properly returning $aArray[x][1] on Classes with instances > 9 when using $2D_ARRAY 10/03/2016 (v0.3): _WinGetClassList Added : Exactly the same as WinGetClassList but returns a more civilized Array _WinGetClassNNList Added : Returns Classes and their instances in either a 1D or 2D array depending on Flags _WindowGetHandleList Renamed: _WinGetHandleList SCRIPT BREAKING! _WindowGetHandleListFromPos Renamed: _WinGetHandleListFromPos SCRIPT BREAKING! 10/01/2016 (v0.2): WindowsExConstants.au3 Added : Flags in _WindowGetHandleListFromPos _WindowGetHandleListFromPos Removed: ConsoleWrite left in during debug _WindowGetHandleListFromPos Added : Flag for if part of a Control is at $X, $Y return it as well. 10/01/2016 (v0.1): _WindowGetHandleList Added : Retrieves the handles of classes from a window. _WindowGetHandleListFromPos Added : Retrieves the handles of classes at a specific position from a window. Known and Reported Bugs:
      None reported To Do:
      To Be Decided. Opinions welcome! Upcoming Changes:
      To Be Decided.
    • FrancescoDiMuro
      By FrancescoDiMuro
      Good morning everyone

      I was playing a little bit with "Screen Capture" UDF, and I was trying to make a "Window" capture, but, since I made a GUI which through I fire the event "Capture", my GUI is captured as well, and I don't want to
      This is the line of code that makes the capture:
       
      _ScreenCapture_CaptureWnd($strScreenCaptureFileName, $objActiveWindow, 0, 0, -1, -1, False) And these are the lines of code which select the "active" window:
       
      Local $objCurrentWindow = 9999 If _IsPressed("01") Then $objCurrentWindow = WinGetHandle("[ACTIVE]") If $objCurrentWindow <> $objMyGUI Then $objActiveWindow = $objCurrentWindow EndIf EndIf Sorry If I made stupid mistakes
      Thanks in advance.

      Francesco
×