func getAddresses(iface net.Interface) (addresses map[string]interface{}, err error) { addresses = make(map[string]interface{}) addrs, err := iface.Addrs() if err != nil { return nil, err } for _, addr := range addrs { var ip net.IP addressInfo := make(map[string]string) switch v := addr.(type) { case *net.IPNet: ip = v.IP case *net.IPAddr: ip = v.IP } netmask := ip.DefaultMask() if netmask != nil { addressInfo["family"] = "inet" } else { addressInfo["family"] = "inet6" } addresses[ip.String()] = addressInfo } mac := iface.HardwareAddr if mac != nil { addressInfo := make(map[string]string) addressInfo["family"] = "lladdr" addresses[mac.String()] = addressInfo } return }
func Mask(addr net.IP) { mask := addr.DefaultMask() network := addr.Mask(mask) ones, bits := mask.Size() fmt.Println("Address is ", addr.String(), " Default mask length is ", bits, "Leading ones count is ", ones, "Mask is (hex) ", mask.String(), " Network is ", network.String()) }
// SpanningCIDR computes network covers given IP addresses func SpanningCIDR(first, last net.IP) *net.IPNet { _, bits := last.DefaultMask().Size() var network net.IPNet for ones := bits; !network.Contains(first); ones-- { network.Mask = net.CIDRMask(ones, bits) network.IP = last.Mask(network.Mask) } return &network }
func (f *summaryFormatter) trackIp(ip net.IP) { for _, net := range f.ipAddrs { if net.Contains(ip) { return } } ipNet := net.IPNet{ip, ip.DefaultMask()} f.ipAddrs = append(f.ipAddrs, ipNet) f.netStrings = append(f.netStrings, ipNet.String()) }
func main() { mn := new(MyNet) ifaces, err := net.Interfaces() if err != nil { log.Fatal(err) } for _, iface := range ifaces { if iface.Flags&net.FlagUp == 0 { continue // interface down } if iface.Flags&net.FlagLoopback != 0 { continue // loopback interface } addrs, err := iface.Addrs() if err != nil { log.Fatal(err) } for _, addr := range addrs { var ip net.IP switch v := addr.(type) { case *net.IPNet: ip = v.IP case *net.IPAddr: // ip = v.IP continue } if ip == nil || ip.IsLoopback() { continue } ip = ip.To4() if ip == nil { continue // not an ipv4 address } fmt.Println("IP: ", ip) fmt.Println("Subnet: ", ip.Mask(ip.DefaultMask())) mn.IP = addr.(*net.IPNet) mn.Subnet = ip.Mask(ip.DefaultMask()) } } fmt.Println(mn) mn.GetNetwork() }
func classfulSubnet(sn net.IP) net.IPNet { return net.IPNet{ IP: sn, Mask: sn.DefaultMask(), } }
func IsIPv4(ip net.IP) bool { return ip.DefaultMask() != nil }