How to print IP address assigned to an interface

Today, I will share a simple way to print an IP address assigned to the specified interface.

It is an easy task, so I will go straight to the point.

Initial notes

I will use three different command to get and print an IP address assigned to the eth0 interface.

ip utility which can used to display and manipulate routing, devices, policy routing and tunnels.

$ ip address show dev eth0 scope global
3: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether f2:3c:91:55:94:b4 brd ff:ff:ff:ff:ff:ff
    inet brd scope global eth0
       valid_lft forever preferred_lft forever
    inet6 2a01:7e01::f03c:91ff:fe55:94b4/64 scope global mngtmpaddr dynamic
       valid_lft 2591982sec preferred_lft 604782sec

ifconfig utility used display and configure network interfaces.

$ sudo ifconfig eth0
eth0      Link encap:Ethernet  HWaddr f2:3c:91:55:94:b4
          inet addr:  Bcast:  Mask:
          inet6 addr: fe80::f03c:91ff:fe55:94b4/64 Scope:Link
          inet6 addr: 2a01:7e01::f03c:91ff:fe55:94b4/64 Scope:Global
          RX packets:40369136 errors:0 dropped:0 overruns:0 frame:0
          TX packets:36417485 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:29721353115 (27.6 GiB)  TX bytes:47788400695 (44.5 GiB)

hostname utility used to print the system's hostname and DNS name.

$ hostname --all-ip-addresses 2a01:7e01::f03c:91ff:fe55:94b4

ip utility

This solution does not require root privileges.

IPv4 address

$ ip address show dev eth0 scope global | awk '/inet / {split($2,var,"/"); print var[1]}'

IPv6 address

$ ip address show dev eth0 scope global | awk '/inet6 / {split($2,var,"/"); print var[1]}'

ifconfig utility

This solution require root privileges.

IPv4 address

$ sudo ifconfig eth0 | awk '/inet / {split($2,var,":"); print var[2]}'

IPv6 address

$ sudo ifconfig eth0 | awk '/inet6 .* Scope:Global/ {split($3,var,"/"); print var[1]}'

hostname utility

This solution can be used to enumerate all configured addresses on all network interfaces, it will ignore loopback interface and IPv6 link-local addresses by default.

$ hostname -I 2a01:7e01::f03c:91ff:fe55:94b4

It should not be included here as you cannot use it to describe specific interface, but I will keep it for further reference.

Milosz Galazka's Picture

About Milosz Galazka

Milosz is a Linux Foundation Certified Engineer working for a successful Polish company as a system administrator and a long time supporter of Free Software Foundation and Debian operating system.