Simple:
ip addr
will return both ipv4 and ipv6 addresses for all network interfaces.
To get ipv4 only use -4
.
Like ip -4 addr
.
To get ipv6 only you need to use -6
.
Like: ip -6 addr
.
To get the ipv4 address only for 1 interface like eth0
use the command:
ip -4 addr show dev eth0
If you want to get litterally only the ipv4 address, then you will have to use some kind of scripting for sure.
But lets say you run the ip command above. This will produce the following in my Ubuntu for WSL:
6: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
inet 172.26.105.98/20 brd 172.26.111.255 scope global eth0
valid_lft forever preferred_lft forever
A quick and dirty way to get the ip addr only would be call the command above, store it in a variable and split text into an array whenever there is a whitespace character (space, newline, tab etc).
The text above will generate an array with 24 elements, when empty elements are removed due to multiple whitespace characters next to each other.
Printing the 15th element in the array will return 172.26.105.98/20
and if you split that element using /
as a seperator will give you 172.26.105.98
.
Ofc there are other ways to do it, by using perl, python or whatever you fancy this is just the dirty version.
Atm im diggin into using regular expression to grab the address from the output above.
Update 2:
Playing more with regexp where I am not particular interested in checking the ip adress is a valid ip adress, since we know it is, gives me the following command.
Using my output from above as basis for the command:
ip -4 addr show dev eth0 | egrep -o 'inet(.*)(brd|scope)' | egrep -o '([0-9]{1,3}\.){3}[0-9]{1,3}'
That will give the output:
172.26.105.98
A quick explanation (in case people dont read the comments).
First we pipe everything from ip addr
to egrep and displaying everything between inet
and brd
or alternative between inet
and scope
.
That is what the command: egrep -o 'inet(.*)(brd|scope)'
do for us.
That gives us:
inet 172.26.105.98/20 brd
on the second time through egrep we are only interested in the ip.
This is being handled by:
egrep -o '([0-9]{1,3}\.){3}[0-9]{1,3}'
This leaves us with only the ipv4 address.
From here you can make a shell script that takes a random device as input and gives you the ipv4 address:
Like making a file name getip.sh
with the following content:
#!/bin/bash
# Call the script with the first agument being the device
DEVICE=$1
ip -4 addr show dev $DEVICE | egrep -o 'inet(.*)(brd|scope)' | egrep -o '([0-9]{1,3}\.){3}[0-9]{1,3}'
You can then call the script with the command getip.sh eth0
and it will return only the ip address.
A few examples using my Ubuntu for WSL:
getip.sh lo
gives 127.0.0.1
getip.sh eth0
gives 172.26.105.98
To do the same for ipv6 addresses is a bit more ... complicated as a regexp for ipv6 is longer...
Hope that answers your question?