How to get the gateway of a dynamic address?

How to change a dynamic address into a it’s gateway in scripting? for example, I got a dynamic address 113.68.141.5,now I want to change it into its gateway form 113.68.141.1,how to acheive it in scripting? and how about change the address into the form like this 113.68.141.0/24?

{:local address 113.68.141.5;
:local gateway;
$gateway=($address-4); ???

# Written by Sam Norris, ChangeIP.com

:log info "Checking default gateway for dhcp interfaces."
:local theName [ /ip dhcp-client get [/ip dhcp-client find status=bound ] interface ] 
:local currentGateway [ /ip dhcp-client get [/ip dhcp-client find status=bound ] gateway ] 
:local existingGateway [ /ip route get [/ip route find comment=$theName] gateway ]
:log info ( $currentGateway . " - " . $existingGateway )

:if ($currentGateway != $existingGateway) do={

  :log info ("Setting default gateway for " . $theName)
  :local a [ /ip route find comment=$theName ]

  :if ([ :typeof $a ] = nil ) do={ 
    :log info "adding route..."
    /ip route add dst-address=0.0.0.0/0 gateway=$currentGateway routing-mark=$theName comment=$theName
   } else={
    :log info "changing route..."
    /ip route set $a gateway=$currentGateway
} else={
  :log info "No route changes needed."
}

I have a cable connection and my ISP offers me dynamic IP address. I was concerned if the DHCP client automatically add the option “Routing Mark” to the added default route, but is not possible…

This script is framed on my needs(I think), but does not want to work.

RouterOS 3.29

[max@core] /system script> run script1
bad argument name else (line 20 column 3)
[max@core] /system script>

It’s missing a closing brace between line 19-20. The final code should look like this:

# Written by Sam Norris, ChangeIP.com

:log info "Checking default gateway for dhcp interfaces."
:local theName [ /ip dhcp-client get [/ip dhcp-client find status=bound ] interface ]
:local currentGateway [ /ip dhcp-client get [/ip dhcp-client find status=bound ] gateway ]
:local existingGateway [ /ip route get [/ip route find comment=$theName] gateway ]
:log info ( $currentGateway . " - " . $existingGateway )

:if ($currentGateway != $existingGateway) do={

  :log info ("Setting default gateway for " . $theName)
  :local a [ /ip route find comment=$theName ]

  :if ([ :typeof $a ] = nil ) do={
    :log info "adding route..."
    /ip route add dst-address=0.0.0.0/0 gateway=$currentGateway routing-mark=$theName comment=$theName
   } else={
    :log info "changing route..."
    /ip route set $a gateway=$currentGateway
   }
} else={
  :log info "No route changes needed."
}

you can also use a routing filter to apply a routing-mark to ‘dynamic-in’ routes. This only doesnt work when you have the need for more than 1 dhcp client.

add a routing-filter in the “dynamic-in” chain the uses set-routing-mark=“myroutingmark”.