使用正则和net包将ip段中的IP提取出来
gopackage main
import (
"fmt"
"net"
"regexp"
"strconv"
"strings"
)
func main() {
input := []string{"192.168.75.[10-244]", "192.168.75.[5-55]", "192.168.75.111", "192.168.75.[140-10]", "192.168.75.133-192.168.75.11", "192.168.75.133-192.168.75.355"}
for _, iprange := range input {
fmt.Printf("Deal iprange: %s\n", iprange)
r, e := IPRangeParser(iprange)
if e != nil {
fmt.Println(e.Error())
}
for _, ip := range r {
fmt.Println(ip.To4().String())
}
}
}
func IPRangeParser(iprange string) ([]net.IP, error) {
//常用的ip范围指定方式:
// 192.168.10.[1-100] 1-100范围
// 192.168.10.1-192.168.10.100 1-100范围
// 192.168.10.100 单个ip
// 处理第一种解析:
if strings.Contains(iprange, "[") || strings.Contains(iprange, "]") {
//使用正则解析:
pattern := `^(\d{1,3}\.\d{1,3}\.\d{1,3})\.\[(\d+)-(\d+)\]$`
re := regexp.MustCompile(pattern)
matchs := re.FindStringSubmatch(iprange)
if len(matchs) != 4 {
return nil, fmt.Errorf("Eroor:Not OK IP Range Format:%s", iprange)
}
prefix := matchs[1]
if net.ParseIP(prefix+".0") == nil {
return nil, fmt.Errorf("Eroor:Not OK IP Range Format:%s", iprange)
}
start, err := strconv.Atoi(matchs[2])
if err != nil {
return nil, fmt.Errorf("Eroor:Not OK IP Start:%s", iprange)
}
end, err := strconv.Atoi(matchs[3])
if err != nil {
return nil, fmt.Errorf("Eroor:Not OK IP End:%s", iprange)
}
if start < 0 || start > 255 || end < 0 || end > 255 || start > end {
return nil, fmt.Errorf("Eroor:Not OK IP Range:%s", iprange)
}
startip := net.ParseIP(fmt.Sprintf("%s.%d", prefix, start)).To4()
endip := net.ParseIP(fmt.Sprintf("%s.%d", prefix, end)).To4()
return GenerateIPs(startip, endip)
} else if strings.Contains(iprange, "-") {
pattern := `^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s*-\s*(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$`
re := regexp.MustCompile(pattern)
matchs := re.FindStringSubmatch(iprange)
if len(matchs) != 3 {
return nil, fmt.Errorf("Eroor:Not OK IP Range Format:%s", iprange)
}
startip := net.ParseIP(matchs[1]).To4()
endip := net.ParseIP(matchs[2]).To4()
if startip == nil || endip == nil {
return nil, fmt.Errorf("Eroor:Not OK IP Range Format:%s", iprange)
}
return GenerateIPs(startip, endip)
} else {
ip := net.ParseIP(iprange)
if ip == nil {
return nil, fmt.Errorf("Eroor:Not OK IP Range Format:%s", iprange)
}
var ips []net.IP
ips = append(ips, ip)
return ips, nil
}
}
func GenerateIPs(start, end net.IP) ([]net.IP, error) {
startUint32 := ipToUint32(start)
endUint32 := ipToUint32(end)
if startUint32 > endUint32 {
return nil, fmt.Errorf("Start %s is bigger then End %s\n", start, end)
}
var ips []net.IP
for i := startUint32; i < endUint32+1; i++ {
ip := uint32ToIP(i)
ips = append(ips, ip)
}
return ips, nil
}
// ipToUint32 将IPv4地址转换为uint32(网络字节序)
func ipToUint32(ip net.IP) uint32 {
ip = ip.To4()
if ip == nil {
return 0
}
return uint32(ip[0])<<24 | uint32(ip[1])<<16 | uint32(ip[2])<<8 | uint32(ip[3])
}
// uint32ToIP 将uint32转换为net.IP
func uint32ToIP(i uint32) net.IP {
return net.IPv4(byte(i>>24), byte(i>>16), byte(i>>8), byte(i))
}