overflow_discovery/discovery/zone.go

89 lines
1.7 KiB
Go
Raw Permalink Normal View History

2017-11-15 12:09:38 +00:00
package discovery
2017-10-20 09:09:07 +00:00
2017-10-26 12:55:55 +00:00
import (
"net"
"regexp"
"strings"
2017-10-20 09:09:07 +00:00
2017-12-04 09:37:39 +00:00
discoveryM "git.loafle.net/overflow/overflow_commons_go/modules/discovery/model"
2017-10-26 12:55:55 +00:00
)
2017-12-04 09:37:39 +00:00
func scanZone(dz *discoveryM.DiscoveryZone, resultChan chan interface{}, errChan chan error, doneChan chan<- struct{}, stopChan chan struct{}) {
2017-11-18 12:08:08 +00:00
defer func() {
doneChan <- struct{}{}
}()
2017-10-20 09:09:07 +00:00
var err error
var ifaces []net.Interface
var addrs []net.Addr
var ipnet *net.IPNet
var zones []*net.IPNet
2017-10-26 12:55:55 +00:00
// var gwIP net.IP
// var gwIFace string
// if gwIP, gwIFace, err = gateway.DiscoverGateway(); nil != err {
// logChan <- err
// return
// }
2017-10-20 09:09:07 +00:00
if ifaces, err = net.Interfaces(); nil != err {
2017-11-15 12:33:46 +00:00
errChan <- err
2017-10-20 09:09:07 +00:00
return
}
zones = make([]*net.IPNet, 0)
for _, i := range ifaces {
if addrs, err = i.Addrs(); nil != err {
2017-11-15 12:33:46 +00:00
errChan <- err
2017-10-20 09:09:07 +00:00
continue
}
for _, addr := range addrs {
2017-10-20 09:20:13 +00:00
2017-10-20 09:09:07 +00:00
if _, ipnet, err = net.ParseCIDR(addr.String()); nil != err {
2017-11-15 12:33:46 +00:00
errChan <- err
2017-10-20 09:09:07 +00:00
continue
}
2017-11-15 12:09:38 +00:00
if ipnet.IP.IsLoopback() || checkSameZone(zones, ipnet) || checkExclude(dz.ExcludePatterns, i.Name) {
2017-10-20 09:09:07 +00:00
continue
}
zones = append(zones, ipnet)
2017-12-04 09:37:39 +00:00
z := &discoveryM.Zone{
2017-10-20 09:20:13 +00:00
Network: ipnet.String(),
Iface: i.Name,
Mac: i.HardwareAddr.String(),
IP: strings.Split(addr.String(), "/")[0],
2017-10-20 09:09:07 +00:00
}
2017-11-15 12:33:46 +00:00
resultChan <- z
2017-10-20 09:09:07 +00:00
}
}
2017-10-26 12:55:55 +00:00
}
2017-10-20 09:09:07 +00:00
2017-10-26 12:55:55 +00:00
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
2017-10-20 09:09:07 +00:00
}
func checkSameZone(zones []*net.IPNet, ipnet *net.IPNet) bool {
for _, i := range zones {
if i.Contains(ipnet.IP) {
return true
}
}
return false
}