Esempio n. 1
0
func GetCidrInfo(network string, logger logger.Logger) (map[string]string, error) {
	network = strings.TrimSpace(network)
	result := make(map[string]string)
	list := strings.Split(network, "/")
	if len(list) != 2 {
		return result, errors.New("网段格式不正确")
	}

	isValidate, err := regexp.MatchString("^((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)$", list[0])
	if err != nil {
		return result, err
	}

	if !isValidate {
		return result, errors.New("IP格式不正确")
	}

	logger.Debugf("get network info:%s", network)

	minIp, maxIp := GetCidrIpRange(network)
	logger.Debugf("get ip range:%s~%s", minIp, maxIp)
	result["MinIP"] = minIp
	result["MaxIP"] = maxIp

	mask, err := strconv.Atoi(list[1])
	if err != nil {
		return result, err
	}

	logger.Debugf("get mask:%d", mask)
	if mask <= 0 || mask >= 32 {
		logger.Error("掩码位不正确!")
		return result, errors.New("掩码位不正确!")
	}

	result["Mask"] = GetCidrIpMask(mask)
	result["IPNum"] = fmt.Sprintf("%d", GetCidrHostNum(mask))
	logger.Debugf("ip nums:%s", result["IPNum"])
	return result, nil
}