Created
December 20, 2022 16:50
-
-
Save lazyfrosch/fb65eaf808d02044a5edd7508b0f7188 to your computer and use it in GitHub Desktop.
golang: Calculating network usable area from
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 net | |
import ( | |
"encoding/binary" | |
"fmt" | |
"net" | |
) | |
// GetNetworkRange returns begin and end address for hosts in a network. | |
// | |
// This range excludes network, gateway (first address) and broadcast address. | |
// | |
// Example: 10.0.0.0/23 would be 10.0.0.2 - 10.0.1.254 | |
func GetNetworkRange(cidr string) (*net.IP, *net.IP, error) { | |
_, network, err := net.ParseCIDR(cidr) | |
if err != nil { | |
return nil, nil, fmt.Errorf("could not parse CIDR: %w", err) | |
} | |
// Convert byte arrays to uint values to apply bit logic | |
// Note: V4 only? | |
uNetwork := binary.BigEndian.Uint32(network.IP) | |
uMask := binary.BigEndian.Uint32(network.Mask) | |
uBroadcast := (uNetwork & uMask) | (uMask ^ 0xffffffff) | |
first := make(net.IP, 4) | |
binary.BigEndian.PutUint32(first, uNetwork+2) | |
last := make(net.IP, 4) | |
binary.BigEndian.PutUint32(last, uBroadcast-1) | |
return &first, &last, nil | |
} |
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 net_test | |
import ( | |
"testing" | |
"github.com/stretchr/testify/assert" | |
) | |
func TestGetNetworkRange(t *testing.T) { | |
first, last, err := net.GetNetworkRange("10.0.0.0/23") | |
assert.NoError(t, err) | |
assert.Equal(t, "10.0.0.2", first.String()) | |
assert.Equal(t, "10.0.1.254", last.String()) | |
first, last, err = net.GetNetworkRange("172.16.0.0/12") | |
assert.NoError(t, err) | |
assert.Equal(t, "172.16.0.2", first.String()) | |
assert.Equal(t, "172.31.255.254", last.String()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment