Skip to content

Commit c5c9b5e

Browse files
committed
logic for finding next available ip
1 parent 70081c1 commit c5c9b5e

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

apiserver/database/cidr.go

+62
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
package database
2+
3+
import (
4+
"fmt"
5+
"net"
6+
"strings"
7+
)
8+
9+
//func main() {
10+
// ips := []string{"10.255.248.1", "10.255.248.3", "10.255.248.2"}
11+
// allocated := make(map[string]struct{})
12+
// for _, allocatedIP := range ips {
13+
// allocated[allocatedIP] = struct{}{}
14+
// }
15+
//
16+
// next, err := FindAvailableIP("10.255.248.0/31", allocated)
17+
// if err != nil {
18+
// panic(err)
19+
// }
20+
// fmt.Println(next)
21+
//}
22+
23+
func FindAvailableIP(cidr string, allocated map[string]struct{}) (string, error) {
24+
ips, _ := cidrIPs(cidr)
25+
for _, ip := range ips {
26+
fmt.Println(ip)
27+
if _, found := allocated[ip]; !found {
28+
return ip, nil
29+
}
30+
}
31+
return "", fmt.Errorf("no available IPs in range %v", cidr)
32+
}
33+
34+
func cidrIPs(cidr string) ([]string, error) {
35+
ip, ipnet, err := net.ParseCIDR(cidr)
36+
37+
if err != nil {
38+
return nil, err
39+
}
40+
41+
var ips []string
42+
for ip := ip.Mask(ipnet.Mask); ipnet.Contains(ip); inc(ip) {
43+
ips = append(ips, ip.String())
44+
}
45+
46+
if strings.HasSuffix(cidr, "/32") {
47+
return ips, nil
48+
} else {
49+
//remove network address and broadcast address
50+
return ips[1 : len(ips)-1], nil
51+
}
52+
}
53+
54+
func inc(ip net.IP) {
55+
fmt.Println([]byte(ip))
56+
for j := len(ip) - 1; j >= 0; j-- {
57+
ip[j]++
58+
if ip[j] > 0 {
59+
break
60+
}
61+
}
62+
}

0 commit comments

Comments
 (0)