--- bin/dhcpd.pl 2009/07/27 22:18:51 12 +++ bin/dhcpd.pl 2009/07/28 10:29:33 17 @@ -8,13 +8,17 @@ use IO::Socket::INET; use Net::DHCP::Packet; use Net::DHCP::Constants; +use File::Slurp; use Data::Dump qw/dump/; die "need to run $0 as root like this\nsudo $0\n" unless $< == 0; my $debug = shift @ARGV; -our ( $server_ip, $file, $next_file ); +our ( $file, $next_file ); +our ( $ip_from, $ip_to ) = ( 10, 100 ); + +our $server_ip = readlink 'conf/server.ip'; my $sock = IO::Socket::INET->new( LocalPort => 67, @@ -28,25 +32,36 @@ Type => SOCK_DGRAM, ) or die "Failed to bind to socket: $@"; -my $_ip = 10; -my $_mac2ip; + +my $addr = $ip_from; sub client_ip { my ( $mac ) = @_; - my $ip = $_mac2ip->{$mac}; - return $ip if $ip; + my $conf = "conf/$server_ip"; + mkdir $conf unless -e $conf; - $ip = $server_ip; - $ip =~ s{\.\d+$}{.$_ip}; - $_mac2ip->{$mac} = $ip; - - $_ip++; - if ( $_ip == 100 ) { - warn "IP roll-over to 10\n"; - $_ip = 10; + if ( -e "$conf/$mac" ) { + my $ip = read_file "conf/mac/$mac"; + print "$mac old $ip\n"; + return $ip; } + mkdir $_ foreach grep { ! -e $_ } map { "$conf/$_" } ( 'ip', 'mac' ); + + my $prefix = $server_ip; + $prefix =~ s{\.\d+$}{.}; + my $ip = $prefix . $addr; + while ( -e "conf/ip/$ip" ) { + $ip = $prefix . $addr++; + die "all addresses allocated!" if $addr == $ip_to; + } + + write_file "$conf/mac/$mac", $ip; + symlink "$conf/mac/$mac", "conf/ip/$ip"; + + print "$mac NEW $ip\n"; + return $ip; } @@ -58,7 +73,7 @@ my $buf; $sock->recv($buf, 1024); - print "<< peer:",$sock->peerhost,":",$sock->peerport,"\n"; + print "<< ",$sock->peerhost,":",$sock->peerport,"\n"; if (defined $buf) {