Programmatically extract private IP address(es)
Anything in the private IP space will always start with one of three IP address blocks.
- 24-bit block - 10.X.X.X
- 20-bit block - 172.16.X.X - 172.31.X.X
- 16-bit block - 192.168.X.X
So just grep for the above types of IP addresses.
$ ifconfig | grep 'inet addr' | cut -d ':' -f 2 | awk '{ print $1 }' | \
grep -E '^(192\.168|10\.|172\.1[6789]\.|172\.2[0-9]\.|172\.3[01]\.)'
192.168.1.20
Details
The grep
I'm using makes use of regular expressions. In this case we're looking for the following patterns:
- 192.168
- 10.
- 172.1[6789].
- 172.2[0-9].
- 172.3[01].
Additionally we're being explicit in only matching numbers which start with one of these patterns. The anchor (^
) is providing this capability to us.
More Examples
If we add the following lines to a file just to test the grep
out.
$ cat afile
192.168.0.1
10.11.15.3
1.23.3.4
172.16.2.4
We can then test it like so:
$ cat afile | grep -E '^(192\.168|10\.|172\.1[6789]\.|172\.2[0-9]\.|172\.3[01]\.)'
192.168.0.1
10.11.15.3
172.16.2.4