如何获得下一个IP地址?(How to get the next IP address?)

编程入门 行业动态 更新时间:2024-10-21 09:17:46
如何获得下一个IP地址?(How to get the next IP address?)

我正在考虑调用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.1

Just 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.1

That 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

更多推荐

本文发布于:2023-07-04 17:01:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1026912.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何获得   地址   IP   address

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!