8 |
use File::Slurp; |
use File::Slurp; |
9 |
use Net::Ping; |
use Net::Ping; |
10 |
|
|
11 |
|
sub mac_path { $server::conf . '/mac/' . $_[0] } |
12 |
|
sub ip_path { $server::conf . '/ip/' . join('/', @_) } |
13 |
|
|
14 |
sub conf { |
sub conf { |
15 |
my $ip = shift; |
my $ip = shift; |
16 |
my $name = shift; |
my $name = shift; |
21 |
$default = $_[1] |
$default = $_[1] |
22 |
} |
} |
23 |
|
|
24 |
my $path ="$server::conf/ip/$ip"; |
my $path = ip_path $ip; |
25 |
mkdir $path unless -d $path; |
mkdir $path unless -d $path; |
26 |
$path .= '/' . $name; |
$path .= '/' . $name; |
27 |
|
|
54 |
return uc($mac); |
return uc($mac); |
55 |
} |
} |
56 |
|
|
57 |
sub next_ip { |
sub next_ip($) { |
58 |
|
my $mac = shift; |
59 |
|
|
60 |
my $p = Net::Ping->new; |
my $p = Net::Ping->new; |
61 |
|
|
64 |
my $addr = $server::ip_from || die; |
my $addr = $server::ip_from || die; |
65 |
my $ip = $prefix . $addr; |
my $ip = $prefix . $addr; |
66 |
|
|
67 |
while ( -e "$server::conf/ip/$ip" || $p->ping( $ip, 0.7 ) ) { |
while ( -e ip_path($ip) || $p->ping( $ip, 0.7 ) ) { |
68 |
$ip = $prefix . $addr++; |
$ip = $prefix . $addr++; |
69 |
die "all addresses allocated!" if $addr == $server::ip_to; |
die "all addresses allocated!" if $addr == $server::ip_to; |
70 |
warn "skip $ip\n"; |
warn "skip $ip\n"; |
71 |
} |
} |
72 |
|
|
73 |
warn "next_ip $ip\n"; |
warn "next_ip $ip\n"; |
74 |
|
|
75 |
|
mkdir ip_path($ip); |
76 |
|
|
77 |
|
symlink ip_path($ip), mac_path($mac); |
78 |
|
write_file ip_path($ip,'mac'), $mac; |
79 |
|
|
80 |
return $ip; |
return $ip; |
81 |
|
|
82 |
} |
} |
83 |
|
|
84 |
sub ip_from_mac { |
sub ip_from_mac($) { |
85 |
my $mac = shift; |
my $mac = shift; |
86 |
|
|
87 |
$mac = lc $mac; |
$mac = lc $mac; |
88 |
$mac =~ s{:}{}g; |
$mac =~ s{:}{}g; |
89 |
|
|
90 |
my $mac_path = "$server::conf/mac/$mac"; |
my $mac_path = mac_path $mac; |
91 |
return unless -e $mac_path; |
return unless -e $mac_path; |
92 |
|
|
93 |
my $ip; |
my $ip; |
95 |
if ( -f $mac_path ) { |
if ( -f $mac_path ) { |
96 |
$ip = read_file $mac_path; |
$ip = read_file $mac_path; |
97 |
unlink $mac_path; |
unlink $mac_path; |
98 |
symlink "$server::conf/ip/$ip", $mac_path; |
symlink ip_path($ip), $mac_path; |
99 |
warn "I: upgrade to mac symlink $mac_path\n"; |
warn "I: upgrade to mac symlink $mac_path\n"; |
100 |
} elsif ( -l $mac_path ) { |
} elsif ( -l $mac_path ) { |
101 |
$ip = readlink $mac_path; |
$ip = readlink $mac_path; |
107 |
return $ip; |
return $ip; |
108 |
} |
} |
109 |
|
|
110 |
|
sub mac_from_ip($) { |
111 |
|
my $ip = shift; |
112 |
|
return read_file ip_path($ip, 'mac'); |
113 |
|
} |
114 |
|
|
115 |
|
sub change_ip($$) { |
116 |
|
my ($old, $new) = @_; |
117 |
|
my $mac = mac_from_ip($old); |
118 |
|
rename ip_path($old), ip_path($new); |
119 |
|
unlink mac_path($mac); |
120 |
|
symlink ip_path($new), mac_path($mac); |
121 |
|
} |
122 |
|
|
123 |
1; |
1; |