Finding Your Public IP Address in Shell Script

November 2016

An Internet Protocol address, or IP address as it is commonly known, is a unique identification number assigned to a computer connected to a network. There are several ways users can retrieve their publicIP addresses. One can use Shell script to know about their public IP address. There are Shell commands which can get the job done. One of them is the GET command which shows the source code of the page. The other option is to use Lynx. Otherwise users can use the Sed command to display their IP address.


Find Your Public IP Address Using Shell

For several reasons, we may need to recover our public IP address in a script.

However, when you are on a LAN, it is difficult to the IP without human intervention.

Implementation

The easiest way is to use a simple command seeking IP in a web page chosen:
  • GET www.monip.org | sed -nre 's/^.* (([0-9]{1,3}\.){3}[0-9]{1,3}).*$/\1/p'


or
  • lynx --source www.monip.org | sed -nre 's/^.* (([0-9]{1,3}\.){3}[0-9]{1,3}).*$/\1/p'


or

GET

The GET command (lwp-request) is founding 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 read more
  • 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 ;).

Related :

This document entitled « Finding Your Public IP Address in Shell Script » from CCM (ccm.net) is made available under the Creative Commons license. You can copy, modify copies of this page, under the conditions stipulated by the license, as this note appears clearly.