Perl – One-liner to Get Local IP Address, No Modules

The code in this post will enable you to identify your system's local IP address and put it into a variable for your further use. I specifically did this to identify the IP address on a Ubuntu WSL2 instance (i.e. Windows Subsystem for Linux), but it should work on any machine. As anyone familiar with WSL2 will know, unlike the prior version of WSL, WSL2 doesn't keep a static IP address, which can be a pain, providing a new one on each startup. So being able to identify the newly allocated IP at startup can be quite handy.

Perl IP Address

Perl, Obtain Local IP Address

There are no doubt numerous other ways to obtain the IP address, but this particular way, using Perl, was useful for what I needed.

Feel free to copy the code given below, for your own purposes:


use strict;
use warnings;

my $ip = `ip addr show eth0 | grep -oP '(?<=inet\\s)\\d+(\\.\\d+){3}'`;

print "$ip\n";