-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
0a6c8c2
commit c8c61a6
Showing
2 changed files
with
76 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,74 @@ | ||
package utils | ||
|
||
import ( | ||
"fmt" | ||
"github.com/wonderivan/logger" | ||
"math/big" | ||
"net" | ||
"os" | ||
"strings" | ||
) | ||
|
||
// ParseIPs 解析ip 192.168.0.2-192.168.0.6 | ||
func ParseIPs(ips []string) []string { | ||
return DecodeIPs(ips) | ||
} | ||
|
||
func DecodeIPs(ips []string) []string { | ||
var res []string | ||
var port string | ||
for _, ip := range ips { | ||
port = "22" | ||
if ipport := strings.Split(ip, ":"); len(ipport) == 2 { | ||
ip = ipport[0] | ||
port = ipport[1] | ||
} | ||
if iprange := strings.Split(ip, "-"); len(iprange) == 2 { | ||
for Cmp(stringToIP(iprange[0]), stringToIP(iprange[1])) <= 0 { | ||
res = append(res, fmt.Sprintf("%s:%s", iprange[0], port)) | ||
iprange[0] = NextIP(stringToIP(iprange[0])).String() | ||
} | ||
} else { | ||
if stringToIP(ip) == nil { | ||
logger.Error("ip [%s] is invalid", ip) | ||
os.Exit(1) | ||
} | ||
res = append(res, fmt.Sprintf("%s:%s", ip, port)) | ||
} | ||
} | ||
return res | ||
} | ||
|
||
// Cmp compares two IPs, returning the usual ordering: | ||
// a < b : -1 | ||
// a == b : 0 | ||
// a > b : 1 | ||
func Cmp(a, b net.IP) int { | ||
aa := ipToInt(a) | ||
bb := ipToInt(b) | ||
|
||
if aa == nil || bb == nil { | ||
logger.Error("ip range %s-%s is invalid", a.String(), b.String()) | ||
os.Exit(-1) | ||
} | ||
return aa.Cmp(bb) | ||
} | ||
func ipToInt(ip net.IP) *big.Int { | ||
if v := ip.To4(); v != nil { | ||
return big.NewInt(0).SetBytes(v) | ||
} | ||
return big.NewInt(0).SetBytes(ip.To16()) | ||
} | ||
|
||
func intToIP(i *big.Int) net.IP { | ||
return net.IP(i.Bytes()) | ||
} | ||
func stringToIP(i string) net.IP { | ||
return net.ParseIP(i).To4() | ||
} | ||
|
||
// NextIP returns IP incremented by 1 | ||
func NextIP(ip net.IP) net.IP { | ||
i := ipToInt(ip) | ||
return intToIP(i.Add(i, big.NewInt(1))) | ||
} |