Get the IP of the local computer from Perl


Caveat: this is only documented on Windows and may or may not work on other OSs (it doesn’t work on Ubuntu 8.04). Also, if the computer has multiple IP addresses (like a LAN, WLAN and a VLAN IP), there is no telling which IP this will return.

Just a little snippet of code:

print join('.', unpack('C*', gethostbyname(''))), "n";

As per the documentation:

If the name parameter points to an empty string or name is NULL, the returned string is the same as the string returned by a successful gethostname function call (the standard host name for the local computer).

Also, other interesting snippet from the same page:

Note The gethostbyname function does not check the size of the name parameter before passing the buffer. With an improperly sized name parameter, heap corruption can occur.

I wonder if the implementors of libraries for interpreters (Perl, Python, etc) do this check…


One response to “Get the IP of the local computer from Perl”

  1. my @data = `ifconfig`;
    my @data1=split (/ +/, $data[1]);
    my @data2=split (/:/, $data1[2]);
    my $local_ip=$data2[1];

Leave a Reply

Your email address will not be published. Required fields are marked *