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

Fix/support cidr #1

Open
wants to merge 2 commits into
base: lu-master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 26 additions & 35 deletions cmd/subspace/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,7 @@ import (
"path/filepath"
"text/template"
"time"
"strconv"
"strings"
"net"
)

func RandomString(n int) string {
Expand Down Expand Up @@ -72,37 +71,29 @@ set -o xtrace
}

func ipv4address(Number int,IPv4_POOL string) (string,error) {
var err error = nil

var hostcidrS[] string = strings.Split(IPv4_POOL,"/")
cidr, _ := strconv.Atoi(hostcidrS[1])
subnet := ((1<<cidr)-1)
subnetmask := ((1<<32)-1)^subnet

var hostOctetS[] string = strings.Split(hostcidrS[0],".")
var hostOctet[4] int
hostOctet[0], _=strconv.Atoi(hostOctetS[0])
hostOctet[1], _=strconv.Atoi(hostOctetS[1])
hostOctet[2], _=strconv.Atoi(hostOctetS[2])
hostOctet[3], _=strconv.Atoi(hostOctetS[3])
host := (hostOctet[0]<<24)|(hostOctet[1]<<16)|(hostOctet[2]<<8)|(hostOctet[3]<<0)

ip := host|Number
ipOctet := [4]int {(ip>>24)&255, (ip>>16)&255, (ip>>8)&255, (ip>>0)&255}

var ipS string = fmt.Sprintf("%d.%d.%d.%d",ipOctet[0],ipOctet[1],ipOctet[2],ipOctet[3])

if (host&subnet) != 0 {
err = fmt.Errorf("IPv4_POOL=\"%s\"",IPv4_POOL)
}else if (Number&subnetmask) != 0 {
err = fmt.Errorf("Number does not fit in the POOL. Number=%d, POOL=\"/%d\"",Number,cidr)
}else if Number == subnet {
err = fmt.Errorf("Broadcast address. Number=%d, IPv4_POOL=\"%s\", address=\"%s\"",Number,IPv4_POOL,ipS)
}else if Number == 0 {
err = fmt.Errorf("Network address. Number=%d, IPv4_POOL=\"%s\", address=\"%s\"",Number,IPv4_POOL,ipS)
}

return ipS,err
_, ipnet, err := net.ParseCIDR(IPv4_POOL)

if err != nil {
return "",err
}

var int64ip int64 =
int64(ipnet.IP[0])*256*256*256+
int64(ipnet.IP[1])*256*256+
int64(ipnet.IP[2])*256+
int64(ipnet.IP[3])+
int64(Number)

var ip net.IP = net.IPv4(
byte(int64ip/256/256/256),
byte(int64ip/256/256%256),
byte(int64ip/256%256),
byte(int64ip%256),
)

if !ipnet.Contains(ip) {
return "",fmt.Errorf("%d hosts can't fit in network %s.",Number,ipnet)
}

return fmt.Sprint(ip),nil
}