MCPcopy Index your code
hub / github.com/MengMengCode/GetRealityDomain / calculateNetworkAddress

Function calculateNetworkAddress

main.go:564–593  ·  view source on GitHub ↗

calculateNetworkAddress 根据IP地址和子网掩码计算网络地址

(ipStr, mask string)

Source from the content-addressed store, hash-verified

562
563// calculateNetworkAddress 根据IP地址和子网掩码计算网络地址
564func calculateNetworkAddress(ipStr, mask string) (string, error) {
565 ip := net.ParseIP(ipStr)
566 if ip == nil {
567 return "", fmt.Errorf("无效的IP地址")
568 }
569
570 // 转换为IPv4
571 ip = ip.To4()
572 if ip == nil {
573 return "", fmt.Errorf("不是有效的IPv4地址")
574 }
575
576 // 解析掩码位数
577 maskStr := mask[1:] // 去掉/前缀
578 maskBits, err := strconv.Atoi(maskStr)
579 if err != nil {
580 return "", fmt.Errorf("无效的掩码位数")
581 }
582
583 // 创建子网掩码
584 maskValue := net.CIDRMask(maskBits, 32)
585
586 // 计算网络地址
587 network := make(net.IP, 4)
588 for i := 0; i < 4; i++ {
589 network[i] = ip[i] & maskValue[i]
590 }
591
592 return network.String(), nil
593}

Callers 1

mainFunction · 0.85

Calls 1

StringMethod · 0.45

Tested by

no test coverage detected