不负相思意
func main() { ifaces, err := net.Interfaces() if err != nil { panic(err) } for _, iface := range ifaces { addrs, _ := iface.Addrs() for _, addr := range addrs { cidr := addr.String() mask, err := mask(cidr) if err != nil { fmt.Println("extracting mask failed:", err) } i, err := mtoi(mask) if err != nil { fmt.Println("creating uint16 from mask failed:", err) } fmt.Printf("CIDR: %s\tMask: %d\n", cidr, i) } }}// Extracts IP mask from CIDR address.func mask(cidr string) (net.IPMask, error) { _, ip, err := net.ParseCIDR(cidr) return ip.Mask, err}// Converts IP mask to 16 bit unsigned integer.func mtoi(mask net.IPMask) (uint16, error) { var i uint16 buf := bytes.NewReader(mask) err := binary.Read(buf, binary.BigEndian, &i) return i, err}
万千封印
您可以实现如下功能:func parseMask(ipaddr string) (mask string, err error) { removeExtra := regexp.MustCompile("^(.*[\\/])") asd := ipaddr[len(ipaddr)-3:] findSubnet := removeExtra.ReplaceAll([]byte(asd), []byte("")) subnet, err := strconv.ParseInt(string(findSubnet), 10, 64) if err != nil { return "", errors.New("Parse Mask: Error parsing mask") } var buff bytes.Buffer for i := 0; i < int(subnet); i++ { buff.WriteString("1") } for i := subnet; i < 32; i++ { buff.WriteString("0") } masker := buff.String() a, _ := strconv.ParseUint(masker[:8], 2, 64) b, _ := strconv.ParseUint(masker[8:16], 2, 64) c, _ := strconv.ParseUint(masker[16:24], 2, 64) d, _ := strconv.ParseUint(masker[24:32], 2, 64) resultMask := fmt.Sprintf("%v.%v.%v.%v", a, b, c, d) return resultMask, nil}然后调用它:func main() { ifaces, _ := net.Interfaces() for _, iface := range ifaces { localip, _ := iface.Addrs() for _, ip := range localip { done, _ := parseMask(ip.String()) log.Println(done) // 255.255.255.0 } }}