[Shell] Retrieving your public IP
For several reasons, we may need to recover its public IP address in a script.
The problem that arises when you are on a LAN, is to find the IP without human intervention.
Implementation
The easiest way is to use a simple command seeking IP in a web page chosen:
Le moyen le plus simple que j'ai trouvé jusqu'à présent est une simple commande recherchant une ip dans une page web choisie :
GET www.myip.org | sed -nre 's/^.* (([0-9]{1,3}\.){3}[0-9]{1,3}).*$/\1/p'
ou
lynx --source www.myip.org | sed -nre 's/^.* (([0-9]{1,3}\.){3}[0-9]{1,3}).*$/\1/p'
GET
The GET command (lwp-request) is foundin libwww of Perl (package: perl-libwww-perl-version).
As its name suggests it is a GET on a page, it returns the source code of the page.
Lynx
Lynx is a text-based browser in most Linux distributions, easier to install than lwp-request(Perl) if necessary.
Sed
The sed command:
parameters
- -n: small display lines given (related to the parameter"p")
- -r: regular expressions support extended
- -e: expression
- s///: indicates a substitution
- p: the result is displayed (in connection with the "n")
- the parameter
- ^.*(parameter_ip).*$ search for a line containing an IP address
- \1: what is in brackets can be addressed later in the expression using \1.
The line containing the IP address is replaced by the IP address itself;)