nic added

This commit is contained in:
crusader 2018-08-23 13:21:46 +09:00
parent 05ee390bc2
commit 30075ad015
2 changed files with 116 additions and 0 deletions

75
nic/nic.go Normal file
View File

@ -0,0 +1,75 @@
package nic
import (
"net"
omm "git.loafle.net/overflow/model/meta"
omn "git.loafle.net/overflow/model/net"
oun "git.loafle.net/overflow/util-go/net"
oung "git.loafle.net/overflow/util-go/net/gateway"
)
func DiscoverGateway() (net.IP, string, error) {
return oung.DiscoverGateway()
}
func DiscoverInterfaces() ([]*omn.Interface, error) {
gwIP, gwIface, err := DiscoverGateway()
if nil != err {
return nil, err
}
netIfaces, err := net.Interfaces()
if err != nil {
return nil, err
}
ifaces := make([]*omn.Interface, 0)
for _, netIface := range netIfaces {
if netIface.Flags&net.FlagLoopback != 0 || netIface.Flags&net.FlagUp == 0 {
continue
}
iface := &omn.Interface{}
ifaces = append(ifaces, iface)
iface.Iface = netIface.Name
iface.Mac = netIface.HardwareAddr.String()
iface.Addresses = make([]*omn.InterfaceAddress, 0)
netAddrs, err := netIface.Addrs()
if nil != err {
continue
}
LOOP_ADDR:
for _, netAddr := range netAddrs {
_, ipNet, err := oun.ParseCIDR(netAddr.String())
if nil != err {
continue
}
addr := &omn.InterfaceAddress{}
iface.Addresses = append(iface.Addresses, addr)
addr.Address = netAddr.String()
addr.Netmask = ipNet.Mask.String()
addr.Network = ipNet.Network().String()
if gwIface == netIface.Name {
addr.Gateway = gwIP.String()
}
switch ipNet.Version() {
case 4:
addr.MetaIPType = omm.ToMetaIPType(omm.MetaIPTypeEnumV4)
case 6:
addr.MetaIPType = omm.ToMetaIPType(omm.MetaIPTypeEnumV6)
default:
continue LOOP_ADDR
}
}
}
return ifaces, nil
}

41
nic/nic_test.go Normal file
View File

@ -0,0 +1,41 @@
package nic
import (
"log"
"testing"
omm "git.loafle.net/overflow/model/meta"
)
func TestDiscoverGateway(t *testing.T) {
gwIP, gwIface, err := DiscoverGateway()
if err != nil {
log.Fatal(err)
}
t.Log("Gateway found")
t.Log("Iface: ", gwIface)
t.Log("IP: ", gwIP.String())
}
func TestDiscoverInterfaces(t *testing.T) {
ifaces, err := DiscoverInterfaces()
if err != nil {
log.Fatal(err)
}
t.Log("Interface found:")
for _, iface := range ifaces {
t.Log("Iface: ", iface.Iface)
t.Log("Mac: ", iface.Mac)
for _, addr := range iface.Addresses {
t.Log("- IP version: ", omm.ToMetaIPTypeEnum(addr.MetaIPType).String())
t.Log("- IP address: ", addr.Address)
t.Log("- Netmask: ", addr.Netmask)
t.Log("- Network: ", addr.Network)
t.Log("- Gateway: ", addr.Gateway)
}
}
}