- Linux Administration Cookbook
- Adam K. Dean
- 431字
- 2021-07-02 14:24:27
Discerning the IP
On a modern box, this is done with ip, which we'll go into greater depth with later:
$ ip address show
This command will give you information about all the interfaces on your system. In the case of our VMs, it looks like this:
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
link/ether 52:54:00:c9:c7:04 brd ff:ff:ff:ff:ff:ff
inet 10.0.2.15/24 brd 10.0.2.255 scope global noprefixroute dynamic eth0
valid_lft 85733sec preferred_lft 85733sec
inet6 fe80::5054:ff:fec9:c704/64 scope link
valid_lft forever preferred_lft forever
3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
link/ether 08:00:27:4b:03:de brd ff:ff:ff:ff:ff:ff
inet 192.168.33.10/24 brd 192.168.33.255 scope global noprefixroute eth1
valid_lft forever preferred_lft forever
inet6 fe80::a00:27ff:fe4b:3de/64 scope link
valid_lft forever preferred_lft forever
4: eth2: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
link/ether 08:00:27:50:a5:cb brd ff:ff:ff:ff:ff:ff
We know lo is the loopback address, which will always have the 127.0.0.1/8 setup, or some other address in that range.
If you know the device you want explicitly, you can also specify it. In the following code, we've done this with eth1:
$ ip address show dev eth1
Within the printed block, we're looking for the IPv4 address, which is listed as being in the inet family:
3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
link/ether 08:00:27:0d:d9:0c brd ff:ff:ff:ff:ff:ff
inet 192.168.33.10/24 brd 192.168.33.255 scope global noprefixroute eth1
valid_lft forever preferred_lft forever
inet6 fe80::a00:27ff:fe0d:d90c/64 scope link
valid_lft forever preferred_lft forever
We have the IP, 192.168.33.10, and we know the subnet it's in, /24 (255.255.255.0).
If you're a bit lazier and want to save on eye movement, you could use something like the following in a scrip to get this information:
$ ip address show dev eth1 | grep "inet " | awk '{ print $2 }'
192.168.33.10/24