Last active
December 27, 2023 02:26
-
-
Save bmcculley/d93ce0f67bb6cbdb464e408d55aada39 to your computer and use it in GitHub Desktop.
CIDR to ip range
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
// before 1.18 | |
package main | |
import ( | |
"fmt" | |
"log" | |
"net" | |
) | |
func Hosts(cidr string) ([]string, error) { | |
ip, ipnet, err := net.ParseCIDR(cidr) | |
if err != nil { | |
return nil, err | |
} | |
var ips []string | |
for ip := ip.Mask(ipnet.Mask); ipnet.Contains(ip); inc(ip) { | |
ips = append(ips, ip.String()) | |
} | |
// remove network address and broadcast address | |
if len(ips) > 1 { | |
return ips[1 : len(ips)-1], nil | |
} | |
return ips, nil | |
} | |
func inc(ip net.IP) { | |
for j := len(ip) - 1; j >= 0; j-- { | |
ip[j]++ | |
if ip[j] > 0 { | |
break | |
} | |
} | |
} | |
func main() { | |
tmp, err := Hosts("192.168.1.3/32") | |
if err != nil { | |
log.Fatal(err) | |
} | |
fmt.Println(tmp) | |
tmp, err = Hosts("10.168.0.0/16") | |
if err != nil { | |
log.Fatal(err) | |
} | |
fmt.Println(tmp) | |
} |
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
// after 1.18 | |
package main | |
import ( | |
"fmt" | |
"log" | |
"net/netip" | |
) | |
func Hosts(cidr string) ([]netip.Addr, error) { | |
prefix, err := netip.ParsePrefix(cidr) | |
if err != nil { | |
panic(err) | |
} | |
var ips []netip.Addr | |
for addr := prefix.Addr(); prefix.Contains(addr); addr = addr.Next() { | |
ips = append(ips, addr) | |
} | |
if len(ips) < 2 { | |
return ips, nil | |
} | |
return ips[1 : len(ips)-1], nil | |
} | |
func main() { | |
tmp, err := Hosts("192.168.1.3/32") | |
if err != nil { | |
log.Fatal(err) | |
} | |
fmt.Println(tmp) | |
tmp, err = Hosts("10.168.0.0/16") | |
if err != nil { | |
log.Fatal(err) | |
} | |
fmt.Println(tmp) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment