Created
March 1, 2018 19:41
-
-
Save udhos/b468fbfd376aa0b655b6b0c539a88c03 to your computer and use it in GitHub Desktop.
nextIP(): find next IP address in Go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"fmt" | |
"net" | |
) | |
func main() { | |
testNext("foo", "bar") | |
testNext("10.0.0.0", "10.0.0.1") | |
testNext("10.0.0.255", "10.0.1.0") | |
} | |
func testNext(ip, wanted string) { | |
i := net.ParseIP(ip) | |
w := net.ParseIP(wanted) | |
if i == nil || w == nil { | |
fmt.Printf("%s => %s BAD INPUT\n", ip, wanted) | |
return | |
} | |
next := nextIP(i, 1) | |
if bytes.Equal(next, w) { | |
fmt.Printf("%s => %s OK\n", ip, wanted) | |
} else { | |
fmt.Printf("%s => %s FAIL got=%s\n", ip, wanted, next) | |
} | |
} | |
func nextIP(ip net.IP, inc uint) net.IP { | |
i := ip.To4() | |
v := uint(i[0])<<24 + uint(i[1])<<16 + uint(i[2])<<8 + uint(i[3]) | |
v += inc | |
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) | |
} |
どう見るの
??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
youtube