方法1::string转int转byte再转ipmask最后转回int
func ipMaskToInt(netmask string) (int, error) {
ipSplitArr := strings.Split(netmask, ".")
if len(ipSplitArr) != 4 {
return 0, fmt.Errorf("netmask:%v is not valid, pattern should like: 255.255.255.0", netmask)
}
ipv4MaskArr := make([]byte, 4)
for i, value := range ipSplitArr {
intValue, err := strconv.Atoi(value)
if err != nil {
return 0, fmt.Errorf("ipMaskToInt call strconv.Atoi error:[%v] string value is: [%s]", err, value)
}
if intValue > 255 {
return 0, fmt.Errorf("netmask cannot greater than 255, current value is: [%s]", value)
}
ipv4MaskArr[i] = byte(intValue)
}
ones, _ := net.IPv4Mask(ipv4MaskArr[0], ipv4MaskArr[1], ipv4MaskArr[2], ipv4MaskArr[3]).Size()
return ones, nil
}
ipmask转byte转Int转string
func IntToipMask(netmask int) string {
Mask := net.CIDRMask(netmask, 32)
val := make([]byte, len(Mask))
copy(val, Mask)
var s []string
for _, i := range val[:] {
s = append(s, strconv.Itoa(int(i)))
}
return strings.Join(s, ".")
}
方法2:sscanf获取byte转int
var a, b, c, d byte
_, _ = fmt.Sscanf("255.255.255.0", "%d.%d.%d.%d", &a, &b, &c, &d)
one, _ := net.IPv4Mask(a, b, c, d).Size()
sprintf获取byte转string
Mask := net.CIDRMask(21, 32)
s := fmt.Sprintf("%d.%d.%d.%d", Mask[0], Mask[1], Mask[2], Mask[3])