Finding Your Public IP Address in Shell Script

January 2018

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.


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

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



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 is a text-based browser in most Linux distributions, easier to install than lwp-request(Perl) if necessary.


The sed command:

  • -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 ;).
Published by deri58. Latest update on March 15, 2016 at 07:17 AM by ChristinaCCM.
This document, titled "Finding Your Public IP Address in Shell Script," is available under the Creative Commons license. Any copy, reuse, or modification of the content should be sufficiently credited to CCM (
Shell - Accessing last commands in history
Linux - Displaying a file in reverse