dhcpd: support ip pool larger than a class C

This commit is contained in:
nadoo 2020-09-29 18:59:57 +08:00
parent de8c08c7b2
commit a956e5811f
2 changed files with 16 additions and 8 deletions

View File

@ -21,6 +21,7 @@ func init() {
type dpcpd struct{} type dpcpd struct{}
// Run runs the service.
func (*dpcpd) Run(args ...string) { func (*dpcpd) Run(args ...string) {
if len(args) < 3 { if len(args) < 3 {
log.F("[dhcpd] not enough parameters, exiting") log.F("[dhcpd] not enough parameters, exiting")

View File

@ -12,14 +12,12 @@ type Pool struct {
items []*item items []*item
} }
func NewPool(lease time.Duration, ipStart, ipEnd net.IP) (*Pool, error) { // NewPool returns a new dhcp ip pool.
items := make([]*item, 0) func NewPool(lease time.Duration, start, end net.IP) (*Pool, error) {
curip := ipStart.To4() s, e := ip2num(start.To4()), ip2num(end.To4())
for bytes.Compare(curip, ipEnd.To4()) <= 0 { items := make([]*item, 0, e-s+1)
ip := make([]byte, 4) for n := s; n <= e; n++ {
copy(ip, curip) items = append(items, &item{lease: lease, ip: num2ip(n)})
items = append(items, &item{lease: lease, ip: ip})
curip[3]++
} }
rand.Seed(time.Now().Unix()) rand.Seed(time.Now().Unix())
return &Pool{items: items}, nil return &Pool{items: items}, nil
@ -69,3 +67,12 @@ func (i *item) take(addr net.HardwareAddr) net.IP {
} }
return nil 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)}
}