MineCraft RCON Autoit3 Function

v1.0 (updated: Ferbruary 11th 2020)

http://opensource.grisambre.net/rconautoit

The below autoit script allows very simply to control a MineCraft server using the RCON protocol. This was developped with Autoit3 v3 and is free and "open source", and licensed under the GNU GPL 3 - copyleft Nicolas Ricquemaque 2020 [contact: opensource (arobase) grisambre dot net].


Sample code

; Usage example
RCON ("127.0.0.1",25575,"MySecurePassword","time set day")
Exit

#cs

   RCON v1.0 / Nicolas RICQUEMAQUE 2020/02/11 opensource@grisambre.net

   Control A Minecraft server using the RCON protocol (which needs to be enabled in the server.properties file)
   See https://wiki.vg/RCON for protocol details

Parameters :
    $RCON_IP : IP Address of the RCON server to connect To
    $RCON_Port : TCP port of the RCON server
    $RCON_passwd : RCON password
    $RCON_command : Command to send to server

Response :
   Success : returns a string with answer from server
   Failure : @error set (1=Connexion Error, 2=No response to auth, 3=Bad password, 4=No response to command) and string with text error

#ce
Func RCON($RCON_IP, $RCON_Port, $RCON_passwd, $RCON_command)
   ; Let's try to connect to MineCraft RCON
   TCPStartup()
   Local $iSocket = TCPConnect($RCON_IP, $RCON_Port)
   If @error Then
      TCPShutdown()
      SetError(1)
      Return "Connection error"
   EndIf

   ; Sending authentication packet
   Local $RCON_ID=Hex(Random(0,2^31-1,1),8)
   Local $RCON_len=Hex(4+4+StringLen($RCON_passwd)+2)
   Local $RCON_send="0x" & StringMid($RCON_len,7,2) & StringMid($RCON_len,5,2) & StringMid($RCON_len,3,2) & StringMid($RCON_len,1,2) & $RCON_ID & "03000000" & _StringToHex ($RCON_passwd) & "0000"
   TCPSend($iSocket, Binary($RCON_send))
   Local $response=TCPRecv ( $iSocket, 256 ,1 )
   If StringLen($response)<10 Then
      TCPCloseSocket($iSocket)
      TCPShutdown()
      SetError(2)
      Return "No response to auth")
   EndIf

   ; Checking authentication answer
   Local $RCON_ID_RESPONSE=BinaryMid($response,5,4)
   If "0x"&$RCON_ID <> $RCON_ID_RESPONSE Then
      TCPCloseSocket($iSocket)
      TCPShutdown()
      SetError(3)
      Return "Bad password"
   EndIf

   ; Sending command packet
   Local $RCON_ID=Hex(Random(0,2^31-1,1),8)
   Local $RCON_len=Hex(4+4+StringLen($RCON_command)+2)
   Local $RCON_send="0x" & StringMid($RCON_len,7,2) & StringMid($RCON_len,5,2) & StringMid($RCON_len,3,2) & StringMid($RCON_len,1,2) & $RCON_ID & "02000000" & _StringToHex ($RCON_command) & "0000"
   TCPSend($iSocket, Binary($RCON_send))
   Local $response=TCPRecv ( $iSocket, 2000 ,1 )
   TCPCloseSocket($iSocket)
   TCPShutdown()

   ; Returning answer
   If StringLen($response)<27 Then
      SetError(4)
      Return "No response to command"
   Else
      Return BinaryToString(BinaryMid($response,13))
   EndIf
EndFunc