Go: how to calculate the number of available IP addresses in a subnet

Go: how to calculate the number of available IP addresses in a subnet

In this article, we will see how to implement a function in Go to calculate the number of available IP addresses in a given subnet.

Calculating the number of available IP addresses in a subnet is a crucial operation in network management, especially when predicting the size of a network or configuring networking for applications and services. Using the Go programming language, we can develop a utility that allows us to perform this calculation efficiently. In this article, we will see how to implement a function in Go to calculate the number of available IP addresses in a given subnet.

Before diving into the code, it is essential to understand some basic networking concepts:

  • IP Address: A unique address assigned to each device on a network.
  • Subnet Mask: Used to divide the address IP in a 'network' and a 'host part'.
  • CIDR (Classless Inter-Domain Routing): A notation used to specify the subnet mask, e.g. 192.168.1.0/24 where /24 indicates that the first 24 bits of the address are the network part.

The formula to calculate the number of available addresses in a subnet is:

Number of addresses = 2(32-bit number of netmask)

For a subnet with a 24-bit netmask (commonly expressed as /24 or 255.255.255.0), the calculation would be:

2(32-24) = 256

Of these 256 addresses, one is reserved for the network address and one for the broadcast, thus leaving 254 usable addresses for hosts.

Here's how you might implement a function in Go that calculates the number of usable IP addresses in a subnet:


package main

import (
     "fmt"
     "math"
     "net"
     "os"
)

// calculateIPs calculates the number of IP addresses that can be used in a CIDR subnet.
func calculateIPs(cidr string) (int, error) {
     _, ipv4Net, err := net.ParseCIDR(cidr)
     if err != nil {
         return 0, err
     }
     maskSize, _ := ipv4Net.Mask.Size()

     totalIPs := int(math.Pow(2, float64(32-maskSize))) - 2
     if totalIPs < 0 {
         totalIPs = 0 // Handles the case of subnets with masks /31 and /32
     }
     return totalIPs, nil
}

func main() {
     if len(os.Args) < 2 {
         fmt.Println("Usage: go run main.go <CIDR>")
         os.Exit(1)
     }
     cidr := os.Args[1]

     count, err := calculateIPs(cidr)
     if err != nil {
         fmt.Println("Error calculating IP addresses:", err)
         os.Exit(1)
     }
     fmt.Printf("Number of usable IP addresses for %s: %d\n", cidr, count)
}

In conclusion, this simple but effective tool in Go allows you to quickly calculate the number of usable IP addresses in any CIDR subnet. It is useful for system administrators and anyone who works with configuring networks. By understanding this tool, you can easily expand or modify your code to include additional networking features.