Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I determine the local machine's IP addresses from Perl?

Is there a clean and OS independent way to determine the local machine's IP addresses from Perl?

So far I have found the following solutions:

  • parse the output of ifconfig and ipconfig (hard, different windows versions have different ipconfig outputs)

  • establish a network connection to a well-known IP and examine the socket's local IP address (won't work if I can't establish a connection and will determine only one IP address)

Any better suggestion?

like image 504
Zizzencs Avatar asked Dec 01 '08 10:12

Zizzencs


1 Answers

You also have some other options, including your solution to "establish a network connection to a well-known IP and examine the socket's local IP address".

In that case (establishing network connection) however, that article points out that:

there is no such thing as a host's IP address.
Network interfaces have IP addresses, not hosts, and a single network interface can have many (virtual) IP addresses. The operating system's routing subsystem decides which network interface and IP address to use to connect to a remote machine.

If your machine only has one external network interface, and this interface only has one IP address then this IP address is commonly called the machine's address, but that is inaccurate.
For example, if the machine is connected to a VPN via a virtual interface it will use this interface's IP address to connect to another machine on the VPN, not the external IP address

Amongst the other solutions: Sys::Hostname - works if it comes up with a resolvable hostname.

use Sys::Hostname;
use Socket;
my $addr = inet_ntoa((gethostbyname(hostname))[4]);
print "$addr\n";
like image 150
VonC Avatar answered Sep 22 '22 03:09

VonC