You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
star/httpreverse/iputil.go

85 lines
1.8 KiB
Go

package httpreverse
import (
"strconv"
"strings"
)
func IPCIDR(ip string) (string, int, error) {
if !strings.Contains(ip, "/") {
return ip, 32, nil
}
tmp := strings.Split(ip, "/")
cidr, err := strconv.Atoi(tmp[1])
if err != nil {
return "", 0, err
}
intIp, err := IP2Int(tmp[0])
if err != nil {
return "", 0, err
}
ip, err = Int2IP(int((uint32(intIp) >> (32 - cidr)) << (32 - cidr)))
return ip, cidr, err
}
func IPEnd(ip string, cidr int) (string, error) {
intIp, err := IP2Int(ip)
if err != nil {
return "", err
}
ip, err = Int2IP(int(uint32(intIp) | ((uint32(4294967295) << cidr) >> cidr)))
return ip, err
}
func IPStart(ip string, cidr int) (string, error) {
intIp, err := IP2Int(ip)
if err != nil {
return "", err
}
ip, err = Int2IP(int((uint32(intIp) >> (32 - cidr)) << (32 - cidr)))
return ip, err
}
func IPInRange(cidrip, ip string) (bool, error) {
w, c, err := IPCIDR(cidrip)
if err != nil {
return false, err
}
f, _, err := IPCIDR(ip + "/" + strconv.Itoa(c))
if err != nil {
return false, err
}
return w == f, nil
}
func IPinRange2(startIP string, cidr int, ip string) (bool, error) {
f, _, err := IPCIDR(ip + "/" + strconv.Itoa(cidr))
if err != nil {
return false, err
}
return startIP == f, nil
}
func IP2Int(ipAddr string) (int, error) {
var ipNum uint32 = 0
ipFilter := strings.Split(ipAddr, ".")
for i := 0; i < len(ipFilter); i++ {
num, err := strconv.ParseUint(ipFilter[len(ipFilter)-1-i], 10, 32)
ipNum |= (uint32(num) << (8 * uint32(i)))
if err != nil {
return 0, err
}
}
return int(ipNum), nil
}
func Int2IP(intIP int) (string, error) {
var result string
var ip uint32
ip = uint32(intIP)
for i := 0; i < 4; i++ {
result += strconv.FormatUint(uint64(uint8(ip>>uint8((3-i)*8))), 10) + "."
}
return result[0 : len(result)-1], nil
}