IP地址从maxAddress开始

I've a need where I need to start generating IP addresses given a CIDR and some cached address. I've some code here where I'm doing bytes.Compare with stored address and only select those that are greater.

https://play.golang.org/p/yT_Mj4fR_jK

What is going wrong here? Basically I need all the addresses from "62.76.47.9" in "62.76.47.12/28". Generating the IPs in the given CIDR range is wellknown.

Thank you.

If you print ìpMax, you'll see its underlying representation is using 16 bytes. (see also the docs

fmt.Printf("'%#v'
",ipMax)

'net.IP{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xff, 0xff, 0x3e, 0x4c, 0x2f, 0x9}'

You can convert ipMax to an IPv4 representation to have your desired results:

ipMax := net.ParseIP("62.76.47.9").To4()

This example will print addresses starting from the first address of 62.76.47.12/28 up to 62.76.47.9.

Playground: https://play.golang.org/p/MUtbiKaQ_3-

package main

import (
    "fmt"
    "net"
)

func main() {
    cidr := "62.76.47.12/28"
    _, ipnet, _ := net.ParseCIDR(cidr)
    ipFirst := ipnet.IP
    ipFirstValue := toHost(ipFirst)

    ipLast := net.ParseIP("62.76.47.9")
    ipLastValue := toHost(ipLast)

    fmt.Println("cidr:  ", cidr)
    fmt.Println("first: ", ipFirst)
    fmt.Println("last:  ", ipLast)

    if ipLastValue < ipFirstValue {
        fmt.Println("ugh")
        return
    }

    for i := ipFirstValue; i < ipLastValue; i++ {
        addr := toIP(i)
        fmt.Println(addr)
    }
}

func toHost(ip net.IP) uint32 {
    i := ip.To4()
    return uint32(i[0])<<24 + uint32(i[1])<<16 + uint32(i[2])<<8 + uint32(i[3])
}

func toIP(v uint32) net.IP {
    v3 := byte(v & 0xFF)
    v2 := byte((v >> 8) & 0xFF)
    v1 := byte((v >> 16) & 0xFF)
    v0 := byte((v >> 24) & 0xFF)
    return net.IPv4(v0, v1, v2, v3)
}