end0tknr's kipple - 新web写経開発

http://d.hatena.ne.jp/end0tknr/ から移転しました

perl経由のpingとarpコマンドで、macアドレスに該当するIPを探索

こんな感じかなぁ

#!/usr/local/bin/perl
use strict;

my $DEST_MAC_ADDR = '00:ff:dd:49:2f:76';
my @DHCP_IP_REALM = map("192.168.0.$_", 1..10); #depend on router dhcp config
my $PING_CMD= '/bin/ping -c 1 -w 1';
my $ARP_CMD= '/sbin/arp -e';

main();

sub main {
    my $found_ip = '';	#DESTINATION IP

    for my $ip ( @DHCP_IP_REALM ){
	#write to arp table
	my $ping_cmd = "$PING_CMD $ip";
	open(my $fh_ping,'-|',$ping_cmd) or die "can't open command: $ping_cmd";
	close($fh_ping);

	#look up arp table
	my $arp_cmd = "$ARP_CMD $ip";
	open(my $fh_arp,'-|',$arp_cmd) or die "can't open command: $arp_cmd";
	$found_ip = lookup_arp_tbl(<$fh_arp>);
	close($fh_arp) or die "can't close command: $arp_cmd";

	last if $found_ip;
    }

    if ( $found_ip ){
	print "DESTINATION IP is $found_ip\n";
    } else {
	print "DESTINATION IP is NOT FOUND\n";
    }
}

sub lookup_arp_tbl {
    my (@arp_responses) = @_;

    for my $arp_res ( @arp_responses ){
	if ($arp_res =~ /^(\d+\.\d+\.\d+\.\d+) .+ $DEST_MAC_ADDR/o){
	    return $1;
	}
    }
    return undef;
}
__END__