November 4, 2024
Listing local ip address of the system

When connected to the internet, the computer in use has a public ip address (or external ip address) that is assigned by the ISP and which is how it appears to the visiting websites and then there is the local ip address (or internal ip address) which is how it can be identified locally to other systems.

Let’s suppose that we need a simple Linux shell script that offers a menu based choice like press 1 for displaying local ip address and press 2 for public ip address.(By the way, to learn the very basics of Linux shell scripting, please refer to our step wise earlier primer here.)

For this:

1. Create a shell script using any text editor (like gedit, nano , vi) :

nano findip.sh

Then copy the following :

#!/bin/bash
# A simple menu driven script for finding out local and public ip address of the system
# Demonstrated for fun by guys at ihaveapc.com

echo " Please select your choice number from below or hit Ctrl-C to exit:"
echo "---------------------------------------------------------------------------------------------"
echo "Press 1 to list local ip address of this system"
echo "Press 2 to find out public ip address of this system"
echo ""

# Read the choice from user and store in variable named choice
read choice

#Use case to match the variable value and do appropriate stuff
case $choice in
1)
echo "Hi $USER"
echo ""
echo "The local ip address of this system is :"
echo "-------------------------------------------------------------"
ip addr show;;

2)
echo "Hi $USER"
echo ""
echo "The public ip address of this system is :"
echo "--------------------------------------------------------------------------"
wget -qO - icanhazip.com;;

*) echo "Not a valid choice! Please rerun the script and enter a valid choice, either 1 or 2";;
esac

Once done, save the contents of the shell script (findip.sh in this case) and make it executable by typing :

chmod a+x findip.sh

Finally, when this shell script is run, we get:

Listing local ip address of the system

Listing public ip address of the system

The first choice when selected will list the ip address details of all the available interfaces of the system. The second choice uses wget (refer to this earlier post on how useful wget can be for downloading files) by using the -q and -O parameters followed by the website queried (icanhazip.com). This website only displays the IP address in text form and nothing else making it ideal for putting it in scripts like one above.

These two parameters run wget in quiet mode and concatenate the output from the queried website thereby displaying only the public ip address.

Happy scripting.

By admin

Related Post

One thought on “A Menu Based Linux Shell Script To Display Local And Public IP Addresses Of The System”

Comments are closed.