From a956e5811fa218044c1e292782283688de305b65 Mon Sep 17 00:00:00 2001 From: nadoo <287492+nadoo@users.noreply.github.com> Date: Tue, 29 Sep 2020 18:59:57 +0800 Subject: [PATCH] dhcpd: support ip pool larger than a class C --- service/dhcpd/dhcpd.go | 1 + service/dhcpd/pool.go | 23 +++++++++++++++-------- 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/service/dhcpd/dhcpd.go b/service/dhcpd/dhcpd.go index 167010c..028c131 100644 --- a/service/dhcpd/dhcpd.go +++ b/service/dhcpd/dhcpd.go @@ -21,6 +21,7 @@ func init() { type dpcpd struct{} +// Run runs the service. func (*dpcpd) Run(args ...string) { if len(args) < 3 { log.F("[dhcpd] not enough parameters, exiting") diff --git a/service/dhcpd/pool.go b/service/dhcpd/pool.go index b8ef7ac..4b9165d 100644 --- a/service/dhcpd/pool.go +++ b/service/dhcpd/pool.go @@ -12,14 +12,12 @@ type Pool struct { items []*item } -func NewPool(lease time.Duration, ipStart, ipEnd net.IP) (*Pool, error) { - items := make([]*item, 0) - curip := ipStart.To4() - for bytes.Compare(curip, ipEnd.To4()) <= 0 { - ip := make([]byte, 4) - copy(ip, curip) - items = append(items, &item{lease: lease, ip: ip}) - curip[3]++ +// NewPool returns a new dhcp ip pool. +func NewPool(lease time.Duration, start, end net.IP) (*Pool, error) { + s, e := ip2num(start.To4()), ip2num(end.To4()) + items := make([]*item, 0, e-s+1) + for n := s; n <= e; n++ { + items = append(items, &item{lease: lease, ip: num2ip(n)}) } rand.Seed(time.Now().Unix()) return &Pool{items: items}, nil @@ -69,3 +67,12 @@ func (i *item) take(addr net.HardwareAddr) net.IP { } return nil } + +func ip2num(ip net.IP) uint32 { + n := uint32(ip[0])<<24 + uint32(ip[1])<<16 + return n + uint32(ip[2])<<8 + uint32(ip[3]) +} + +func num2ip(n uint32) net.IP { + return []byte{byte(n >> 24), byte(n >> 16), byte(n >> 8), byte(n)} +}