overflow_discovery/net/zone.go
crusader 44bc4f51d8 ing
2017-10-26 21:55:55 +09:00

115 lines
2.0 KiB
Go

package net
import (
"net"
"regexp"
"strings"
"git.loafle.net/overflow/overflow_discovery/net/model"
)
type ZoneScanner interface {
}
type zoneScan struct {
config *DiscoveryZoneConfig
endChan chan bool
zoneChan chan *model.DiscoveryZone
logChan chan error
}
func newZoneScan(dzc *DiscoveryZoneConfig) *zoneScan {
zs := &zoneScan{
config: dzc,
endChan: make(chan bool),
zoneChan: make(chan *model.DiscoveryZone, 4),
logChan: make(chan error, 4),
}
return zs
}
func (zs *zoneScan) Close() {
close(zs.endChan)
close(zs.zoneChan)
close(zs.logChan)
}
func scanZone(zs *zoneScan) {
var err error
var ifaces []net.Interface
var addrs []net.Addr
var ipnet *net.IPNet
var zones []*net.IPNet
// var gwIP net.IP
// var gwIFace string
// if gwIP, gwIFace, err = gateway.DiscoverGateway(); nil != err {
// logChan <- err
// return
// }
if ifaces, err = net.Interfaces(); nil != err {
zs.logChan <- err
return
}
zones = make([]*net.IPNet, 0)
for _, i := range ifaces {
if addrs, err = i.Addrs(); nil != err {
zs.logChan <- err
continue
}
for _, addr := range addrs {
if _, ipnet, err = net.ParseCIDR(addr.String()); nil != err {
zs.logChan <- err
continue
}
if ipnet.IP.IsLoopback() || checkSameZone(zones, ipnet) || checkExclude(zs.config.ExcludePatterns, i.Name) {
continue
}
zones = append(zones, ipnet)
dz := &model.DiscoveryZone{
Network: ipnet.String(),
Iface: i.Name,
Mac: i.HardwareAddr.String(),
IP: strings.Split(addr.String(), "/")[0],
}
zs.zoneChan <- dz
}
}
zs.endChan <- true
}
func checkExclude(ep []string, iface string) bool {
var r *regexp.Regexp
var err error
for _, p := range ep {
if r, err = regexp.Compile(p); nil != err {
return false
}
if r.MatchString(iface) {
return true
}
}
return false
}
func checkSameZone(zones []*net.IPNet, ipnet *net.IPNet) bool {
for _, i := range zones {
if i.Contains(ipnet.IP) {
return true
}
}
return false
}