8 |
use IO::Socket::INET; |
use IO::Socket::INET; |
9 |
use Net::DHCP::Packet; |
use Net::DHCP::Packet; |
10 |
use Net::DHCP::Constants; |
use Net::DHCP::Constants; |
11 |
|
use File::Slurp; |
12 |
use Data::Dump qw/dump/; |
use Data::Dump qw/dump/; |
13 |
|
|
14 |
die "need to run $0 as root like this\nsudo $0\n" unless $< == 0; |
die "need to run $0 as root like this\nsudo $0\n" unless $< == 0; |
15 |
|
|
16 |
my $debug = shift @ARGV; |
my $debug = shift @ARGV; |
17 |
|
|
18 |
our ( $server_ip, $file, $next_file ); |
our ( $file, $next_file ); |
19 |
|
our ( $ip_from, $ip_to ) = ( 10, 100 ); |
20 |
|
|
21 |
|
our $server_ip = readlink 'conf/server.ip'; |
22 |
|
|
23 |
my $sock = IO::Socket::INET->new( |
my $sock = IO::Socket::INET->new( |
24 |
LocalPort => 67, |
LocalPort => 67, |
32 |
Type => SOCK_DGRAM, |
Type => SOCK_DGRAM, |
33 |
) or die "Failed to bind to socket: $@"; |
) or die "Failed to bind to socket: $@"; |
34 |
|
|
35 |
my $_ip = 10; |
|
36 |
my $_mac2ip; |
my $addr = $ip_from; |
37 |
|
|
38 |
sub client_ip { |
sub client_ip { |
39 |
my ( $mac ) = @_; |
my ( $mac ) = @_; |
40 |
|
|
41 |
my $ip = $_mac2ip->{$mac}; |
my $conf = "conf/$server_ip"; |
42 |
return $ip if $ip; |
mkdir $conf unless -e $conf; |
43 |
|
|
44 |
$ip = $server_ip; |
if ( -e "$conf/$mac" ) { |
45 |
$ip =~ s{\.\d+$}{.$_ip}; |
my $ip = read_file "conf/mac/$mac"; |
46 |
$_mac2ip->{$mac} = $ip; |
print "$mac old $ip\n"; |
47 |
|
return $ip; |
|
$_ip++; |
|
|
if ( $_ip == 100 ) { |
|
|
warn "IP roll-over to 10\n"; |
|
|
$_ip = 10; |
|
48 |
} |
} |
49 |
|
|
50 |
|
mkdir $_ foreach grep { ! -e $_ } map { "$conf/$_" } ( 'ip', 'mac' ); |
51 |
|
|
52 |
|
my $prefix = $server_ip; |
53 |
|
$prefix =~ s{\.\d+$}{.}; |
54 |
|
my $ip = $prefix . $addr; |
55 |
|
while ( -e "conf/ip/$ip" ) { |
56 |
|
$ip = $prefix . $addr++; |
57 |
|
die "all addresses allocated!" if $addr == $ip_to; |
58 |
|
} |
59 |
|
|
60 |
|
write_file "$conf/mac/$mac", $ip; |
61 |
|
symlink "$conf/mac/$mac", "conf/ip/$ip"; |
62 |
|
|
63 |
|
print "$mac NEW $ip\n"; |
64 |
|
|
65 |
return $ip; |
return $ip; |
66 |
} |
} |
67 |
|
|
73 |
|
|
74 |
my $buf; |
my $buf; |
75 |
$sock->recv($buf, 1024); |
$sock->recv($buf, 1024); |
76 |
print "<< peer:",$sock->peerhost,":",$sock->peerport,"\n"; |
print "<< ",$sock->peerhost,":",$sock->peerport,"\n"; |
77 |
|
|
78 |
if (defined $buf) { |
if (defined $buf) { |
79 |
|
|