2019-05-02 16:05:14 +00:00
|
|
|
package fakeip
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"net"
|
2019-05-23 15:27:29 +00:00
|
|
|
"sync"
|
2019-05-02 16:05:14 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// Pool is a implementation about fake ip generator without storage
|
|
|
|
type Pool struct {
|
|
|
|
max uint32
|
|
|
|
min uint32
|
|
|
|
offset uint32
|
2019-05-23 15:27:29 +00:00
|
|
|
mux *sync.Mutex
|
2019-05-02 16:05:14 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Get return a new fake ip
|
|
|
|
func (p *Pool) Get() net.IP {
|
2019-05-23 15:27:29 +00:00
|
|
|
p.mux.Lock()
|
|
|
|
defer p.mux.Unlock()
|
2019-05-02 16:05:14 +00:00
|
|
|
ip := uintToIP(p.min + p.offset)
|
|
|
|
p.offset = (p.offset + 1) % (p.max - p.min)
|
|
|
|
return ip
|
|
|
|
}
|
|
|
|
|
|
|
|
func ipToUint(ip net.IP) uint32 {
|
|
|
|
v := uint32(ip[0]) << 24
|
|
|
|
v += uint32(ip[1]) << 16
|
|
|
|
v += uint32(ip[2]) << 8
|
|
|
|
v += uint32(ip[3])
|
|
|
|
return v
|
|
|
|
}
|
|
|
|
|
|
|
|
func uintToIP(v uint32) net.IP {
|
|
|
|
return net.IPv4(byte(v>>24), byte(v>>16), byte(v>>8), byte(v))
|
|
|
|
}
|
|
|
|
|
|
|
|
// New return Pool instance
|
|
|
|
func New(ipnet *net.IPNet) (*Pool, error) {
|
|
|
|
min := ipToUint(ipnet.IP) + 1
|
|
|
|
|
|
|
|
ones, bits := ipnet.Mask.Size()
|
|
|
|
total := 1<<uint(bits-ones) - 2
|
|
|
|
|
|
|
|
if total <= 0 {
|
|
|
|
return nil, errors.New("ipnet don't have valid ip")
|
|
|
|
}
|
|
|
|
|
|
|
|
max := min + uint32(total)
|
|
|
|
return &Pool{
|
|
|
|
min: min,
|
|
|
|
max: max,
|
2019-05-23 15:27:29 +00:00
|
|
|
mux: &sync.Mutex{},
|
2019-05-02 16:05:14 +00:00
|
|
|
}, nil
|
|
|
|
}
|