Skip to content

Commit

Permalink
Merge pull request #1 from vaskoz/suggestions
Browse files Browse the repository at this point in the history
Suggestions for performance improvements
  • Loading branch information
andy-trimble authored Jul 12, 2021
2 parents 97c97f2 + 30f27e7 commit 219a806
Showing 1 changed file with 19 additions and 33 deletions.
52 changes: 19 additions & 33 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,67 +6,53 @@ import (
"log"
"net"
"os"
"strconv"
"strings"
"text/tabwriter"
)

func inc(ip net.IP) {
for j := len(ip) - 1; j >= 0; j-- {
ip[j]++
if ip[j] > 0 {
break
}
}
}

func main() {
log.SetPrefix("")
log.SetFlags(0)

var ipRange string
var err error

if len(os.Args) > 1 {
// The range was passed in as an argument
ipRange = os.Args[1]
} else {
// Read from standard input
reader := bufio.NewReader(os.Stdin)
ipRange, err = reader.ReadString('\n')
if err != nil {
log.Fatal(err)
}
ipRange = strings.TrimSpace(ipRange)
ipRange, _ = reader.ReadString('\n')
}

spl := strings.Split(ipRange, "/")
if len(spl) < 2 {
log.Fatal("bad cidr")
}
r, err := strconv.Atoi(spl[1])
ipRange = strings.TrimSpace(ipRange)
addr, network, err := net.ParseCIDR(ipRange)
if err != nil {
log.Fatal(err)
}
if r < 8 {
log.Fatal("range cannot be smaller than 8")
}

addr, network, err := net.ParseCIDR(ipRange)
if err != nil {
log.Fatal(err)
ipv4 := addr.To4()
if ipv4 == nil {
log.Fatal("built for IPv4 only")
}

var ips []string
for ip := addr.Mask(network.Mask); network.Contains(ip); inc(ip) {
ips = append(ips, ip.String())
subnetMask := network.Mask
firstIp := make([]byte, len(ipv4))
lastIp := make([]byte, len(ipv4))
numIPs := 0

for i := range ipv4 {
firstIp[i] = ipv4[i] & subnetMask[i]
lastIp[i] = ipv4[i] | (subnetMask[i] ^ 0xff)
numIPs <<= 8
numIPs += int(subnetMask[i] ^ 0xff)
}

w := tabwriter.NewWriter(os.Stdout, 0, 0, 1, ' ', 0)
fmt.Fprintf(w, "CIDR Range:\t%s\n", network)
fmt.Fprintf(w, "Netmask:\t%d.%d.%d.%d\n", network.Mask[0], network.Mask[1], network.Mask[2], network.Mask[3])
fmt.Fprintf(w, "First IP:\t%s\n", ips[0])
fmt.Fprintf(w, "Last IP:\t%s\n", ips[len(ips)-1])
fmt.Fprintf(w, "Addresses:\t%d\n", len(ips))
fmt.Fprintf(w, "First IP:\t%s\n", net.IP(firstIp))
fmt.Fprintf(w, "Last IP:\t%s\n", net.IP(lastIp))
fmt.Fprintf(w, "Addresses:\t%d\n", numIPs+1)
w.Flush()
}

0 comments on commit 219a806

Please sign in to comment.