|
| 1 | +package utils |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "github.com/wonderivan/logger" |
| 6 | + "math/big" |
| 7 | + "net" |
| 8 | + "os" |
| 9 | + "strings" |
| 10 | +) |
| 11 | + |
| 12 | +// ParseIPs 解析ip 192.168.0.2-192.168.0.6 |
| 13 | +func ParseIPs(ips []string) []string { |
| 14 | + return DecodeIPs(ips) |
| 15 | +} |
| 16 | + |
| 17 | +func DecodeIPs(ips []string) []string { |
| 18 | + var res []string |
| 19 | + var port string |
| 20 | + for _, ip := range ips { |
| 21 | + port = "22" |
| 22 | + if ipport := strings.Split(ip, ":"); len(ipport) == 2 { |
| 23 | + ip = ipport[0] |
| 24 | + port = ipport[1] |
| 25 | + } |
| 26 | + if iprange := strings.Split(ip, "-"); len(iprange) == 2 { |
| 27 | + for Cmp(stringToIP(iprange[0]), stringToIP(iprange[1])) <= 0 { |
| 28 | + res = append(res, fmt.Sprintf("%s:%s", iprange[0], port)) |
| 29 | + iprange[0] = NextIP(stringToIP(iprange[0])).String() |
| 30 | + } |
| 31 | + } else { |
| 32 | + if stringToIP(ip) == nil { |
| 33 | + logger.Error("ip [%s] is invalid", ip) |
| 34 | + os.Exit(1) |
| 35 | + } |
| 36 | + res = append(res, fmt.Sprintf("%s:%s", ip, port)) |
| 37 | + } |
| 38 | + } |
| 39 | + return res |
| 40 | +} |
| 41 | + |
| 42 | +// Cmp compares two IPs, returning the usual ordering: |
| 43 | +// a < b : -1 |
| 44 | +// a == b : 0 |
| 45 | +// a > b : 1 |
| 46 | +func Cmp(a, b net.IP) int { |
| 47 | + aa := ipToInt(a) |
| 48 | + bb := ipToInt(b) |
| 49 | + |
| 50 | + if aa == nil || bb == nil { |
| 51 | + logger.Error("ip range %s-%s is invalid", a.String(), b.String()) |
| 52 | + os.Exit(-1) |
| 53 | + } |
| 54 | + return aa.Cmp(bb) |
| 55 | +} |
| 56 | +func ipToInt(ip net.IP) *big.Int { |
| 57 | + if v := ip.To4(); v != nil { |
| 58 | + return big.NewInt(0).SetBytes(v) |
| 59 | + } |
| 60 | + return big.NewInt(0).SetBytes(ip.To16()) |
| 61 | +} |
| 62 | + |
| 63 | +func intToIP(i *big.Int) net.IP { |
| 64 | + return net.IP(i.Bytes()) |
| 65 | +} |
| 66 | +func stringToIP(i string) net.IP { |
| 67 | + return net.ParseIP(i).To4() |
| 68 | +} |
| 69 | + |
| 70 | +// NextIP returns IP incremented by 1 |
| 71 | +func NextIP(ip net.IP) net.IP { |
| 72 | + i := ipToInt(ip) |
| 73 | + return intToIP(i.Add(i, big.NewInt(1))) |
| 74 | +} |
0 commit comments