1
0
mirror of https://github.com/zu1k/nali.git synced 2025-01-24 06:09:01 +08:00
nali/internal/tools/ipparser.go

55 lines
1.2 KiB
Go
Raw Normal View History

2020-07-21 17:23:38 +08:00
package tools
2020-07-17 10:52:36 +08:00
import (
2020-09-28 08:26:08 +08:00
"net"
2020-07-17 10:52:36 +08:00
"regexp"
"strings"
)
var (
2020-09-07 10:23:35 +08:00
ipv4re *regexp.Regexp
2020-07-18 09:52:59 +08:00
ipv6re0 *regexp.Regexp
ipv6re *regexp.Regexp
2020-07-17 10:52:36 +08:00
)
func init() {
ipv4re = regexp.MustCompile(`(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}`)
2020-07-18 09:52:59 +08:00
ipv6re0 = regexp.MustCompile(`^fe80:(:[0-9a-fA-F]{1,4}){0,4}(%\w+)?|([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|(([0-9a-fA-F]{1,4}:){0,6}[0-9a-fA-F]{1,4})?::(([0-9a-fA-F]{1,4}:){0,6}[0-9a-fA-F]{1,4})?$`)
ipv6re = regexp.MustCompile(`fe80:(:[0-9a-fA-F]{1,4}){0,4}(%\w+)?|([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|(([0-9a-fA-F]{1,4}:){0,6}[0-9a-fA-F]{1,4})?::(([0-9a-fA-F]{1,4}:){0,6}[0-9a-fA-F]{1,4})?`)
2020-07-17 10:52:36 +08:00
}
func GetIP4FromString(str string) []string {
str = strings.Trim(str, " ")
return ipv4re.FindAllString(str, -1)
}
2020-07-18 09:52:59 +08:00
func GetIP6FromString(str string) []string {
str = strings.Trim(str, " ")
return ipv6re.FindAllString(str, -1)
}
2020-09-07 10:23:35 +08:00
2020-09-28 08:26:08 +08:00
const (
ValidIPv4 = iota
ValidIPv6
InvalidIP
)
2020-09-07 10:23:35 +08:00
2020-09-28 08:26:08 +08:00
type Valid int
2020-09-28 08:26:08 +08:00
func ValidIP(IP string) (v Valid) {
for i := 0; i < len(IP); i++ {
switch IP[i] {
case '.':
v = ValidIPv4
case ':':
v = ValidIPv6
2020-09-07 10:23:35 +08:00
}
}
2020-09-28 08:26:08 +08:00
if ip := net.ParseIP(IP); ip != nil {
return v
}
return InvalidIP
2020-09-07 10:23:35 +08:00
}