Jump to content

Winsock UDF

Recommended Posts


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
    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
                $nCode = $aRet[0]
            If $nCode = 0 Then $nCode = -3 ;undefined error
        If $nCode = -10 Then $nCode = 0
        $nReturn = -1

        $nReturn = $aRet
    Return SetError($nCode, 0, $nReturn)

EndFunc   ;==>_TCPKeepAlive


Windows Registry Editor Version 5.00


;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,



"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

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

    • caramen
      By caramen
      I watched _OL_ItemSend&_OL_ItemFind&_OL_ItemCreate in OutlookEx UDF but hmmm
      Since it use the test environnement i cant get the orders of the mail creation
      Can someone make me win some time of reading all exemples script and lead me how to do one ?
      That whould be lovely.
    • Tersion
      By Tersion
      Here the this wiki page with list of available UDFs for data compression. For my tasks I only need ZIP support, so I started looking at pure AutoIt UDFs without any 3rd party dlls. And found out that most of available realizations uses standard ("native method") Windows dll - "zipfldr.dll". So for now I chose ZIP UDF by wraithdu. I've tested it on Windows 7 (x64) and it seem works fine. But here the comment from another topic where user says that Windows 10 discontinued support of "zipfldr.dll". Now I confused. I don't have around any Windows 10 machine to tested it. So maybe someone could confirm or deny that? Or maybe would better to switch to UDF with 7zip dll?
      I need an advice...
    • TheSaint
      By TheSaint
      Here is the bare bones of a UDF I have started work on.
      Mostly just a proof of concept at this stage, and still need to add some functions and dress the UDF up a bit ... to look like a UDF ... though it has my own distinct styling, especially as I have never really developed a UDF before now .... used plenty and modified plenty though. I've even invented my own UDF variable naming convention, which I am sure some of you will be aghast at. I work with what feels best for me, but others are free to adapt if they wish.
      The idea is to emulate the simplicity of INI files, but gain the benefits of SQL.
      Two scripts are provided.
      (1) The UDF, a work in progress - SimpleSQL_UDF.au3
      (2) An example or testing script - UDF_Test.au3
      Another first for me, is creating a 2D array from scratch, never done that before, that I can recall ... never had a need, and even for 1 dimension arrays, for a long time now, I have just used _StringSplit to create them. So I needed a bit of a refresher course, which my good buddy @TheDcoder assisted me with ... not without some angst I might add. LOL
      SimpleSQL_UDF.zip  (12 downloads previously)
      (I have now completed all the functions I intended to. My next update will be a big improvement, bringing things more inline with my latest INItoSQL DB program changes.)
      Program requires the sqlite3.dll, not included, but easily enough obtained.
      Hopefully the usage is self-evident ... just change the Job number variable in the UDF_Test.au3 file to check the existing functions out.
      P.S. This is also related to a new program I have just finished and uploaded - INItoSQL DB
    • xtcislove
      By xtcislove
      as a start in Autoit i tried something i was missing since im using Autoit. 

      I build a custom MessageBox which has a large amount of custom options and which scales its size on the parameters you set. 

      Aviable Settings:
      -Unlimited Buttons
      -Text Color (Buttons, Text)

      -Background Color (Msgbox, Buttons, Label) 

      -Button Timeout
      -Autoclose Timeout
      -Icon (Default, No Icon, Custom)

      -Label/ Button Style. 

      I tried to keep this as close as i could to a Msgbox i was used too on my batch times.

      After i was ready i realised, @Melba23 probably build a way better msgbox which would have suit my needs enterly, anyway thanks to @Melba23 because i use his Stringsize UDF. 

      local $Message = _sMsgBox("Test", 6, "Continue?") if @extended <> -1 Then MsgBox(0, @extended, $Message&" Button pressed")  
    • 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.