A few words of thanks would be greatly appreciated.

Finding Your Public IP Address in Shell Script

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 www.monip.org | sed -nre 's/^.* (([0-9]{1,3}\.){3}[0-9]{1,3}).*$/\1/p'

  • lynx --source www.monip.org | 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 ;).

A few words of thanks would be greatly appreciated.

Ask a question
CCM is a leading international tech website. Our content is written in collaboration with IT experts, under the direction of Jeff Pillou, founder of CCM.net. CCM reaches more than 50 million unique visitors per month and is available in 11 languages.
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 (https://ccm.net/).