// 将ip格式的掩码转换为整型数字
// 如 255.255.255.0 对应的整型数字为 24
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
}
golang将IP格式的掩码转换为整型数字
最新推荐文章于 2023-02-22 16:03:17 发布