Page 1 of 1

Find External IP ?

Posted: Mon Jun 03, 2013 6:50 pm
by ahead
In this scenario How can I Find The Public Ip behind the modem By mikrotik script ?

Users<-->Switch<-->Mikrotik<--------->Modem<----?--->Internet

*Modem Get Dynamic And Public IP From Internet.
*Mikrotik Get Local IP From Modem By DHCP.

Re: Find External IP ?

Posted: Mon Jun 03, 2013 7:08 pm
by c0d3rSh3ll
this script check your publick ip and return in a local variable.

ros code

{
/tool fetch url="http://myip.dnsomatic.com/" mode=http dst-path=mypublicip.txt
local ip [file get mypublicip.txt contents ]
put $ip
}

Re: Find External IP ?

Posted: Wed Jun 05, 2013 5:56 am
by jrpaz
is there any way you can make it print the variable or does it have to save to a file.

Re: Find External IP ?

Posted: Wed Jun 05, 2013 11:37 pm
by c0d3rSh3ll
is necessary download the file to get the public ip. The script get the public ip from the file and put it to a variable.

Re: Find External IP ?

Posted: Sat Jun 08, 2013 1:27 pm
by ahead
Solved:

#Get Ip And Save it To "mypublicip.txt" File In Mikrotik
/tool fetch url="http://myip.dnsomatic.com/mypublicip.txt" mode=http
#Save Ip From "mypublicip.txt" File To "MyVar" Variable
:local myvar [file get mypublicip.txt contents ]
#Write Ip From "MyVar" Variable To Mikrotik Log
/log info message=$myvar

Re: Find External IP ?

Posted: Mon Jul 29, 2013 3:20 pm
by anoka
Hi!

Here is a script to query and set the external interface IP address.

Copy to Winbox System/Scripts menu
Name: Refresh_External_IP
Source:

ros code

# Set needed variables
:global extinterface "ether1-gateway"
:global ExtIpListName "external-ip"
:global extip ""
:global oldextip ""

# Grab the current IP address on that interface.
:local extip2 [/ip address get [/ip address find interface=$extinterface ] address];
:set extip [:pick $extip2 0 [:find $extip2 "/"]];
:log info "Current external IP = $extip"

:if ([:len [/ip firewall address-list find list=$ExtIpListName]] > 0) do={
   :set oldextip [/ip firewall address-list get [/ip firewall address-list find list=$ExtIpListName] address];
   :if ($oldextip != $extip) do={
      /ip firewall address-list set [/ip firewall address-list find list=$ExtIpListName address=$oldextip] address=$extip
     :log info "External IP relpace from $oldextip to $extip"
   } else={
     :log info "External IP not changed"
   };
} else={
   /ip firewall address-list add list=$ExtIpListName address=$extip
   :log info "New external IP added: $extip"
};
Copy to terminal:

plain code

add name=Refresh_External_IP policy=ftp,read,write,test,winbox,api source="# S\
    et needed variables\r\
    \n:global extinterface \"ether1-gateway\"\r\
    \n:global ExtIpListName \"external-ip\"\r\
    \n:global extip \"\"\r\
    \n:global oldextip \"\"\r\
    \n\r\
    \n# Grab the current IP address on that interface.\r\
    \n:local extip2 [/ip address get [/ip address find interface=\$extinterfac\
    e ] address];\r\
    \n:set extip [:pick \$extip2 0 [:find \$extip2 \"/\"]];\r\
    \n:log info \"Current external IP = \$extip\"\r\
    \n\r\
    \n:if ([:len [/ip firewall address-list find list=\$ExtIpListName]] > 0) d\
    o={\r\
    \n   :set oldextip [/ip firewall address-list get [/ip firewall address-li\
    st find list=\$ExtIpListName] address];\r\
    \n   :if (\$oldextip != \$extip) do={\r\
    \n      /ip firewall address-list set [/ip firewall address-list find list\
    =\$ExtIpListName address=\$oldextip] address=\$extip\r\
    \n     :log info \"External IP relpace from \$oldextip to \$extip\"\r\
    \n   } else={\r\
    \n     :log info \"External IP not changed\"\r\
    \n   };\r\
    \n} else={\r\
    \n   /ip firewall address-list add list=\$ExtIpListName address=\$extip\r\
    \n   :log info \"New external IP added: \$extip\"\r\
    \n};\r\
    \n"
Use as is free! :)

Re: Find External IP ?

Posted: Sat Dec 21, 2013 11:23 am
by zap71
I posted a slightly modified version of anoka's script and a php-script which handles the "external" server part if you want to host this on a self-owned web server.

The whole thing can be found in Determine External IP Address With RouterOS on Harry's TechBlog.

Re: Find External IP ?

Posted: Sat Feb 27, 2016 11:08 am
by jimmyz
Hello to all.
A small comment on zap71's post/script, in "<<SOURCE_LABEL>>"
.../myrosip.php?who=<<SOURCE_LABEL>>" mode=http dst-path=mypublicip.txt
avoid using any spaces, like "Fantastic ROS". It makes the server sad :(
2016-02-27 10:30:03	Error	xx.xx.128.85	403	GET /myrosip.php?who=Fantastic ROS HTTP/1.0		Mikrotik/6.x Fetch	462 	Apache access
2016-02-27 10:30:03	Error	xx.xx.128.85		ModSecurity: [file "/etc/httpd/crs/activated_rules/modsecurity_crs_20_protocol_violations.conf"] [line "52"] [id "960911"] [rev "2"] [msg "Invalid HTTP Request Line"] [data "GET /myrosip.php?who=Fantastic ROS HTTP/1.0"] [severity "WARNING"] [ver "OWASP_CRS/2.2.8"] [maturity "9"] [accuracy "9"] [tag "OWASP_CRS/PROTOCOL_VIOLATION/INVALID_REQ"] [tag "CAPEC-272"] Warning. Match of "rx ^(?i:(?:[a-z]{3,10}\\\\s+(?:\\\\w{3,7}?://[\\\\w\\\\-\\\\./]*(?::\\\\d+)?)?/[^?#]*(?:\\\\?[^#\\\\s]*)?(?:#[\\\\S]*)?|connect (?:\\\\d{1,3}\\\\.){3}\\\\d{1,3}\\\\.?(?::\\\\d+)?|options \\\\*)\\\\s+[\\\\w\\\\./]+|get /[^?#]*(?:\\\\?[^#\\\\s]*)?(?:#[\\\\S]*)?)$" against "REQUEST_LINE" required. [hostname "mysite.com"] [uri "/myrosip.php"] [unique_id "VtFei5BMStIADvtxPsMAAAAV"]				Apache error
2016-02-27 10:30:03	Error	xx.xx.128.85		ModSecurity: [file "/etc/httpd/crs/activated_rules/modsecurity_crs_30_http_policy.conf"] [line "78"] [id "960034"] [rev "2"] [msg "HTTP protocol version is not allowed by policy"] [data "ROS HTTP/1.0"] [severity "CRITICAL"] [ver "OWASP_CRS/2.2.8"] [maturity "9"] [accuracy "9"] [tag "OWASP_CRS/POLICY/PROTOCOL_NOT_ALLOWED"] [tag "WASCTC/WASC-21"] [tag "OWASP_TOP_10/A6"] [tag "PCI/6.5.10"] Warning. Match of "within %{tx.allowed_http_versions}" against "REQUEST_PROTOCOL" required. [hostname "mysite.com"] [uri "/myrosip.php"] [unique_id "VtFei5BMStIADvtxPsMAAAAV"]				Apache error
2016-02-27 10:30:03	Error	xx.xx.128.85		ModSecurity: [file "/etc/httpd/crs/activated_rules/modsecurity_crs_49_inbound_blocking.conf"] [line "26"] [id "981176"] [msg "Inbound Anomaly Score Exceeded (Total Score: 5, SQLi=0, XSS=0): Last Matched Message: HTTP protocol version is not allowed by policy"] [data "Last Matched Data: GET /myrosip.php?who=Fantastic ROS HTTP/1.0"] Access denied with code 403 (phase 2). Pattern match "(.*)" at TX:960911-OWASP_CRS/PROTOCOL_VIOLATION/INVALID_REQ-REQUEST_LINE. [hostname "mysite.com"] [uri "/myrosip.php"] [unique_id "VtFei5BMStIADvtxPsMAAAAV"]				Apache error
2016-02-27 10:30:03	Error	xx.xx.128.85		ModSecurity: [file "/etc/httpd/crs/activated_rules/modsecurity_crs_60_correlation.conf"] [line "37"] [id "981204"] [msg "Inbound Anomaly Score Exceeded (Total Inbound Score: 5, SQLi=0, XSS=0): HTTP protocol version is not allowed by policy"] Warning. Operator GE matched 5 at TX:inbound_anomaly_score. [hostname "mysite.com"] [uri "/myrosip.php"] [unique_id "VtFei5BMStIADvtxPsMAAAAV"]

Re: Find External IP ?

Posted: Fri Jul 29, 2016 2:34 am
by GuilhermePinheiro
this script check your publick ip and return in a local variable.

ros code

{
/tool fetch url="http://myip.dnsomatic.com/" mode=http dst-path=mypublicip.txt
local ip [file get mypublicip.txt contents ]
put $ip
}
Thanks very much... I used this on the script for DDNS update...
1. Criar script (código abaixo) com o nome no-ip_ddns_update

2. criar a scheduler(ou colar a linha abaixo no terminal).
/system scheduler add comment="Update No-IP DDNS" disabled=no interval=5m \
name=no-ip_ddns_update on-event=no-ip_ddns_update policy=read,write,test


Código Script:

# Atualização automática de DNS Dinâmico NO-IP

#--------------- Defina os valores nessa sessão para configurar ------------------

# Informações de acesso NO-IP
:local noipuser "EMAIL OU NOME DE LOGIN DO NOIP"
:local noippass "SENHA DE LOGIN"

# Defina o nome do servidor da web a ter o IP atualizado.
# O nome do servidor não aceita espaços. Substitua o valor entre as aspas pelo nome(URL) do seu servidor.
# Para especificar vários servidores, separe-os com vírgulas.
:local noiphost "HOST, EX.: host.ddns.net"


#------------------------------------------------------------------------------------
# Não precisa alterar mais nada

:global previousIP

/tool fetch url="http://myip.dnsomatic.com/" mode=http dst-path=mypublicip.txt
:local currentIP [file get mypublicip.txt contents]

# Strip the net mask off the IP address
   :for i from=( [:len $currentIP] - 1) to=0 do={
       :if ( [:pick $currentIP $i] = "/") do={ 
           :set currentIP [:pick $currentIP 0 $i]
       } 
 }

   :if ($currentIP != $previousIP) do={
       :log info "No-IP: O ip atual $currentIP não é igual ao IP anterior, atualização necessária"
       :set previousIP $currentIP

# The update URL. Note the "\3F" is hex for question mark (?). Required since ? is a special character in commands.
       :local url "http://dynupdate.no-ip.com/nic/update\3Fmyip=$currentIP"
       :local noiphostarray
       :set noiphostarray [:toarray $noiphost]
       :foreach host in=$noiphostarray do={
           :log info "No-IP: Sending update for $host"
           /tool fetch url=($url . "&hostname=$host") user=$noipuser password=$noippass mode=http dst-path=("no-ip_ddns_update-" . $host . ".txt")
           :log info "No-IP: Servidor $host atualizado com o IP $currentIP"
       }
   }  else={
       :log info "No-IP: IP anterior $previousIP é igual o IP atual, atualização não necessária."
   }

Re: Find External IP ?

Posted: Sun Jul 31, 2016 9:15 pm
by thiagomedeiros
is there any way you can make it print the variable or does it have to save to a file.
Yes, you can do this:
:global currentIP [:resolve myip.opendns.com server=208.67.222.222];

Will always return your public IP. Not needed to download/fetch a file.

Re: Find External IP ?

Posted: Mon Dec 05, 2016 3:08 am
by codeck
and then Please How to put the public IP into ip firewall Nat automaticly, I need to ridirecting from ip public to local router

Re: Find External IP ?

Posted: Mon Dec 05, 2016 7:39 pm
by raxs
Example
To enable and activate this service:
[admin@MikroTik] /ip cloud set ddns-enabled=yes
[admin@MikroTik] /ip cloud print
ddns-enabled: yes
update-time: yes
public-address: 159.148.172.205
dns-name: 529c0491d41c.sn.mynetname.net
status: updated
To enable time update from cloud service:
[admin@MikroTik] > ip cloud set update-time=yes
To enable automatic time zone detection:
[admin@MikroTik] > system clock set time-zone-autodetect=yes
Properties
Sub-menu: /ip cloud


Tapatalk kullanarak iPhone aracılığıyla gönderildi

Re: Find External IP ?

Posted: Fri Jun 15, 2018 11:20 am
by Maximiliam1st
Credz goes to https://wiki.mikrotik.com/wiki/Dynamic_ ... for_dynDNS

The cloud dns from Mikrotik times out every so often and made me get a paid dyndns account.

The following script and scheduling works perfect in 6.x and works behind NAT / private ip. It will update dyn with your external IP.

Make a script called: dynDNS

Place the following script in the box

[Codebox]
:global ddnsuser "username"
:global ddnspass "password"
:global ddnshost whatever.your.hostname.is
:global ipddns [:resolve $ddnshost];
:global ipfresh [:resolve myip.opendns.com server=208.67.222.222];
:if ([ :typeof $ipfresh ] = nil ) do={
:log info ("DynDNS: No ip address on $theinterface .")
} else={
:for i from=( [:len $ipfresh] - 1) to=0 do={
:if ( [:pick $ipfresh $i] = "/") do={
:set ipfresh [:pick $ipfresh 0 $i];
}
}

:if ($ipddns != $ipfresh) do={
:log info ("DynDNS: IP-DynDNS = $ipddns")
:log info ("DynDNS: IP-Fresh = $ipfresh")
:log info "DynDNS: Update IP needed, Sending UPDATE...!"
:global str "/nic/update\?hostname=$ddnshost&myip=$ipfresh&wildcard=NOCHG&mx=NOCHG&backmx=NOCHG"
/tool fetch address=members.dyndns.org src-path=$str mode=http user=$ddnsuser \
password=$ddnspass dst-path=("/DynDNS.".$ddnshost)
:delay 1
:global str [/file find name="DynDNS.$ddnshost"];
/file remove $str
:global ipddns $ipfresh
:log info "DynDNS: IP updated to $ipfresh!"
} else={
:log info "DynDNS: dont need changes";
}
}
[/Codebox]

Schedule it (enter the following in a terminal window)

[Codebox]
/system scheduler
add interval=1m name=dynDNS on-event=dynDNS policy=ftp,reboot,read,write,policy,test,winbox,password,sniff,sensitive,api start-time=startup
[/Codebox]

Re: Find External IP ?

Posted: Tue Sep 17, 2019 9:34 am
by miankamran7100
this script check your publick ip and return in a local variable.

ros code

{
/tool fetch url="http://myip.dnsomatic.com/" mode=http dst-path=mypublicip.txt
local ip [file get mypublicip.txt contents ]
put $ip
}
Plese write code her when my router rebooted without proper-shutdown then this file send to me in my email

Re: Find External IP ?

Posted: Tue Sep 17, 2019 7:29 pm
by Jotne
Why use all these complicate code, when you can just go to IP Cloud and turn it on. Then router does everything for you.

To get the IP address in code:
:put [/ip cloud get public-address]

Re: Find External IP ?

Posted: Tue Dec 03, 2019 1:00 am
by creatin
Or:

:put [:resolve myip.opendns.com server=208.67.222.222]

Re: Find External IP ?

Posted: Wed Dec 04, 2019 12:54 am
by creatin
This one works:

before you run the script create a file in Windows called currentIP.txt, write inside some IP address like 1.1.1.1, save file and upload it to your router.

Run script below:
:local filename "currentIP.txt"
:local ip [file get currentIP.txt contents];
delay 1
:local cip ([:resolve myip.opendns.com server=208.67.222.222]);
delay 1
:local sub ("New WAN address: $cip");
:local bod ("old WAN IP = $ip \nnew WAN IP = $cip");
delay 3
:if ($ip != $cip) do={/tool e-mail send to="your.email@email.com" subject="$sub" body="$bod";
delay 4
/file set $filename contents=$cip
}
}
Set a scheduler to run the script every 10 minutes (since startup) and it'll send you an email each time your WAN IP address has been changed.
If no change, no emails will be sent.