From 56b95442f70c2e2a8c8667c5943dc2cfb209b0b1 Mon Sep 17 00:00:00 2001 From: dnomd343 Date: Mon, 15 Aug 2022 14:13:10 +0800 Subject: [PATCH] feat: ip address check --- src/main.go | 53 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 src/main.go diff --git a/src/main.go b/src/main.go new file mode 100644 index 0000000..250fddf --- /dev/null +++ b/src/main.go @@ -0,0 +1,53 @@ +package main + +import ( + "fmt" + "net" + "strconv" + "strings" +) + +func isIP(ipAddr string, isRange bool, allowEmpty bool, ipLength int, ipFlag string) bool { + var address string + if allowEmpty && ipAddr == "" { // empty case + return true + } + if isRange { + temp := strings.Split(ipAddr, "/") + if len(temp) != 2 { // not {IP_ADDRESS}/{LENGTH} format + return false + } + length, err := strconv.Atoi(temp[1]) + if err != nil { // range length not a integer + return false + } + if length < 0 || length > ipLength { // length should between 0 ~ ipLength + return false + } + address = temp[0] + } else { + address = ipAddr + } + ip := net.ParseIP(address) // try to convert ip + return ip != nil && strings.Contains(address, ipFlag) +} + +func isIPv4(ipAddr string, isRange bool, allowEmpty bool) bool { + return isIP(ipAddr, isRange, allowEmpty, 32, ".") +} + +func isIPv6(ipAddr string, isRange bool, allowEmpty bool) bool { + return isIP(ipAddr, isRange, allowEmpty, 128, ":") +} + +func main() { + fmt.Println("XProxy") + + fmt.Println(isIPv4("1.1.1.1", false, false)) + fmt.Println(isIPv4("1.1.1.1/24", true, false)) + fmt.Println(isIPv4("", true, true)) + fmt.Println(isIPv4("::1", true, true)) + fmt.Println(isIPv6("::1", true, true)) + fmt.Println(isIPv6("::1/32", true, true)) + fmt.Println(isIPv6("::1", true, true)) +}