Last active
April 16, 2020 14:10
-
-
Save x1unix/5ff0f83dbbefd8cbaaab565bdebcc900 to your computer and use it in GitHub Desktop.
Go - CIDR to IPs
This file contains 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 | |
func IPsFromCIDR(cidr string) ([]net.IP, error) { | |
_, ipNet, err := net.ParseCIDR(cidr) | |
if err != nil { | |
return nil, err | |
} | |
ones, bits := ipNet.Mask.Size() | |
addrCount := 1 << (bits - ones) | |
ip := ipNet.IP | |
result := make([]net.IP, 0, addrCount) | |
for x := 0; x < addrCount; x++ { | |
result = append(result, cloneIP(ip)) | |
incrementIP(ip) | |
} | |
return result, nil | |
} | |
func cloneIP(src net.IP) net.IP { | |
dest := make(net.IP, len(src)) | |
copy(dest, src) | |
return dest | |
} | |
func incrementIP(ip net.IP) { | |
for i := len(ip) - 1; i >= 0; i-- { | |
ip[i]++ | |
//only add to the next byte if we overflowed | |
if ip[i] != 0 { | |
break | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment