HowTo: Read Linux network settings in a shell script

InfoDabble > Tech Notes > Linux > HowTo: Read Linux network settings in a shell script
Jump to: navigation, search

Contents


[edit] How to find/display your IP address

getmyip shell script:
command: ifconfig  | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2 | awk '{ print $1}'
output:      192.168.0.102
command: getmyip | cut -d. -f 4
output:      102

ifconfig and netstat can be used to identify other network settings:

myIP=$(ifconfig | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2 | awk '{ print $1}')
mySubnet=$(ifconfig | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2 | cut -d. -f1,2,3 | awk '{ print $1}')
myMask=$(ifconfig | grep 'Mask:'| grep -v '127.0.0.1' | cut -d: -f4 | awk '{ print $1}')
myBcast=$(ifconfig | grep 'Bcast:'| grep -v '127.0.0.1' | cut -d: -f3 | awk '{ print $1}')
myBase=$(netstat -r | grep $myMask | awk '{ print $1}')
myGateway=$(netstat -r | grep 'default' | awk '{ print $2}')

command: echo $myIP --- $mySubnet --- $myMask --- $myBcast --- $myBase --- $myGateway
output:       192.168.0.101 --- 192.168.0 --- 255.255.255.0 --- 192.168.0.255 --- 192.168.0.0 --- 192.168.0.1


[edit] How to find/display your MAC address

As the root user (or user with appropriate permissions), type

"ifconfig -a" 

From the displayed information, find eth0 (this is the default first Ethernet adapter) locate the number next to the HWaddr. This is your MAC address. The MAC Address will be displayed in the form of 00:08:C7:1B:8C:02.

Example "ifconfig -a" output:

eth0    Link encap:Ethernet HWaddr 00:08:C7:1B:8C:02
           inet addr:192.168.111.20  Bcast:192.168.111.255  Mask:255.255.255.0
           ... additional output removed ...


[edit] How to find/display your Ethernet adapter

It's easy enough to identify the first Ethernet adapter:

myAdapter=$(ifconfig | grep -m1 'encap:Ethernet' | cut -d' ' -f1)

command:  echo $myAdapter
  output:      eth0

Note that this only works with wired adapters and not wireless ones. A more general approach is:

myAdapter=$(ifconfig | grep 'encap:' | grep -m1 -v 'encap:Local' | cut -d' ' -f1)

The filter returns the first network adapter other than the loopback adapter.