Groovy 代码从用 CIDR 表示法表示的给定子网中获取所有可用的 IP 地址

问题描述 投票:0回答:1

我在 Gen AI 的帮助下生成了以下代码,但它返回一个空列表。有人可以帮我调试这个吗?

static List<String> generateAvailableIps(String subnetCidr) {
    // Parse the CIDR notation
    def (ipAddress, subnetMask) = subnetCidr.split("/")

    // Convert IP address to integer
    def ipInt = ipAddress.split("\\.").inject(0) { acc, value -> (acc << 8) + value.toInteger() }

    // Get subnet mask as integer
    def subnetMaskInt = (1 << (32 - subnetMask.toInteger())) - 1

    // Get network address
    def networkAddress = ipInt & subnetMaskInt

    // Get first and last usable IP addresses (excluding network and broadcast)
    def firstUsableIp = networkAddress + 1
    def broadcastAddress = networkAddress | ~subnetMaskInt
    def lastUsableIp = broadcastAddress - 1

    // Generate a list of available IP addresses
    def availableIps = []
    for (int i = firstUsableIp; i <= lastUsableIp; i++) {
        def octet1 = (i >> 24) & 0xff
        def octet2 = (i >> 16) & 0xff
        def octet3 = (i >> 8) & 0xff
        def octet4 = i & 0xff
        availableIps.add("$octet1.$octet2.$octet3.$octet4")
    }

    return availableIps
}

// Example usage
def availableIps = generateAvailableIps("192.168.35.32/27")
println(availableIps)

给定子网中可用的 IP 地址列表

groovy ip-address subnet
1个回答
0
投票
static List<String> generateAvailableIps(String subnetCidr) {
    // Parse the CIDR notation
    def (ipAddress, subnetMask) = subnetCidr.split("/")

    // Convert IP address to integer
    def ipInt = ipAddress.split("\\.").inject(0) { acc, value -> (acc << 8) + value.toInteger() }

    // Get subnet mask as integer
    def subnetMaskInt = (-1 << (32 - subnetMask.toInteger()))

    // Get network address
    def networkAddress = ipInt & subnetMaskInt

    // Get first and last usable IP addresses (excluding network and broadcast)
    def firstUsableIp = networkAddress + 1
    def broadcastAddress = networkAddress | ~subnetMaskInt
    def lastUsableIp = broadcastAddress - 1

    // Generate a list of available IP addresses
    def availableIps = []
    for (int i = firstUsableIp; i <= lastUsableIp; i++) {
        def octet1 = (i >> 24) & 0xff
        def octet2 = (i >> 16) & 0xff
        def octet3 = (i >> 8) & 0xff
        def octet4 = i & 0xff
        availableIps.add("$octet1.$octet2.$octet3.$octet4")
    }

    return availableIps
}
© www.soinside.com 2019 - 2024. All rights reserved.