我正在考虑调用net.IP.String() , strings.Split(ip, ".") ,一些代码来计算所有的net.ParseIP(s)情况,最后是net.ParseIP(s) 。 有更好的方法吗? 下面是我当前实现的代码(没有处理特殊情况)。
package main import ( "fmt" "net" "strconv" "strings" ) func main() { ip := net.ParseIP("127.1.0.0") next, err := NextIP(ip) if err != nil { panic(err) } fmt.Println(ip, next) } func NextIP(ip net.IP) (net.IP, error) { s := ip.String() sa := strings.Split(s, ".") i, err := strconv.Atoi(sa[2]) if err != nil { return nil, err } i++ sa[3] = strconv.Itoa(i) s = strings.Join(sa, ".") return net.ParseIP(s), nil }I'm considering to call net.IP.String(), strings.Split(ip, "."), some code to calculate all the corner cases and finally net.ParseIP(s). Is there a better way to this?. Below is the code of my current implementation (no special case handled).
package main import ( "fmt" "net" "strconv" "strings" ) func main() { ip := net.ParseIP("127.1.0.0") next, err := NextIP(ip) if err != nil { panic(err) } fmt.Println(ip, next) } func NextIP(ip net.IP) (net.IP, error) { s := ip.String() sa := strings.Split(s, ".") i, err := strconv.Atoi(sa[2]) if err != nil { return nil, err } i++ sa[3] = strconv.Itoa(i) s = strings.Join(sa, ".") return net.ParseIP(s), nil }最满意答案
只需增加IP地址中的最后一个八位字节
ip := net.ParseIP("127.1.0.0") // make sure it's only 4 bytes ip = ip.To4() // check ip != nil ip[3]++ // check for rollover fmt.Println(ip) //127.1.0.1然而,这在技术上是不正确的,因为127.1.0.1/8子网中的第一个地址是127.0.0.1。 要获得真正的“第一”地址,您还需要一个IPMask。 由于您没有指定一个,因此您可以将DefaultMask用于IPv4地址(对于IPv6,您不能假设掩码,并且必须提供它)。
http://play.golang.org/p/P_QWwRIBIm
ip := net.IP{192, 168, 1, 10} ip = ip.To4() if ip == nil { log.Fatal("non ipv4 address") } ip = ip.Mask(ip.DefaultMask()) ip[3]++ fmt.Println(ip) //192.168.1.1Just increment the last octet in the IP address
ip := net.ParseIP("127.1.0.0") // make sure it's only 4 bytes ip = ip.To4() // check ip != nil ip[3]++ // check for rollover fmt.Println(ip) //127.1.0.1That however is technically incorrect, since the first address in the 127.1.0.1/8 subnet is 127.0.0.1. To get the true "first" address, you will also need an IPMask. Since you didn't specify one, you could use DefaultMask for IPv4 addresses (for IPv6 you can't assume a mask, and you must provide it).
http://play.golang.org/p/P_QWwRIBIm
ip := net.IP{192, 168, 1, 10} ip = ip.To4() if ip == nil { log.Fatal("non ipv4 address") } ip = ip.Mask(ip.DefaultMask()) ip[3]++ fmt.Println(ip) //192.168.1.1更多推荐
发布评论