[Chicago-talk] Any handy operators for finding the local IP?
Steve Peters
steve at fisharerojo.org
Tue Mar 15 11:45:38 PST 2005
On Tue, Mar 15, 2005 at 08:16:23AM -0800, Richard Reina wrote:
> I know there's a handy $< to find the UID of the user
> executing the prorgram. Is there any handy operator
> to find the IP address of the local machine that is
> running the program.
>
Richard,
The ways to get an IP address from Perl are less than 100% reliable. To
get something reliable, you have to get to a fairly low level on the
device. With the help of Libnet (the C library), Inline::C, and root
access, its a piece of cake.
Enjoy!
Steve Peters
steve at fisharerojo.org
#!/usr/bin/perl -w
use Inline ( C => 'DATA',
LIBS => '-L/usr/local/lib -lnet',
INC => '-I/usr/local/include',
AUTO_INCLUDE => '#include "libnet.h"'
);
print get_ip_address("fxp0"), "\n";
__END__
__C__
char* get_ip_address(char* device) {
char* errbuf[LIBNET_ERRBUF_SIZE];
libnet_t* l;
u_int32_t ip;
char* addr;
l = libnet_init(LIBNET_LINK, device, errbuf);
if (!l) {
addr = libnet_geterror(l);
return addr;
}
ip = libnet_get_ipaddr4(l);
if(-1 == ip) {
addr = libnet_geterror(l);
} else {
addr = libnet_addr2name4(ip, LIBNET_DONT_RESOLVE);
}
libnet_destroy(l);
return addr;
}
More information about the Chicago-talk
mailing list