Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add cidr calc #4

Open
tomdoherty opened this issue Nov 17, 2020 · 0 comments
Open

add cidr calc #4

tomdoherty opened this issue Nov 17, 2020 · 0 comments

Comments

@tomdoherty
Copy link
Owner

e.g.

package main

import (
	"bytes"
	"encoding/binary"
	"fmt"
	"net"
	"sort"
	"strconv"
	"strings"
)

func ip2int(ip net.IP) uint32 {
	if len(ip) == 16 {
		return binary.BigEndian.Uint32(ip[12:16])
	}
	return binary.BigEndian.Uint32(ip)
}

func int2ip(ip uint32) string {
	result := make(net.IP, 4)
	result[0] = byte(ip >> 24)
	result[1] = byte(ip >> 16)
	result[2] = byte(ip >> 8)
	result[3] = byte(ip)
	return result.String()
}

func ips2cidr(ipaddrs []string) string {
	realIPs := make([]net.IP, 0, len(ipaddrs))

	for _, ip := range ipaddrs {
		realIPs = append(realIPs, net.ParseIP(ip))
	}

	sort.Slice(realIPs, func(i, j int) bool {
		return bytes.Compare(realIPs[i], realIPs[j]) < 0
	})

	var and, xor uint32
	and = ip2int(realIPs[0]) & ip2int(realIPs[len(ipaddrs)-1])
	xor = ip2int(realIPs[0]) ^ ip2int(realIPs[len(ipaddrs)-1])

	IPv4 := int2ip(and)
	var mask string
	for _, o := range strings.Split(int2ip(xor), ".") {
		i, err := strconv.Atoi(o)
		if err != nil {
			panic(err)
		}

		asBin := strconv.FormatInt(int64(i), 2)
		out := fmt.Sprintf("%s%s", strings.Repeat("0", 8-len(asBin)), asBin)
		mask += out

	}
	cidr := strings.Index(mask, "1")

	return fmt.Sprintf("%s/%d", IPv4, cidr)
}

func main() {
	ipaddrs := []string{"192.168.1.1", "192.168.2.255", "192.168.3.255"}

	fmt.Println(ips2cidr(ipaddrs))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant