Created
April 12, 2021 15:25
-
-
Save nguyenthang98/784af1798dbb8bb9768d5bc7ee1dca09 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| package main | |
| import ( | |
| "fmt" | |
| "strings" | |
| "strconv" | |
| ) | |
| func makeSeq(min, max int) []int { | |
| a := make([]int, max-min+1) | |
| for i := range a { | |
| a[i] = min + i | |
| } | |
| return a | |
| } | |
| func MinMax(array []int) (int, int) { | |
| var max int = array[0] | |
| var min int = array[0] | |
| for _, value := range array { | |
| if max < value { | |
| max = value | |
| } | |
| if min > value { | |
| min = value | |
| } | |
| } | |
| return min, max | |
| } | |
| func parseString(str string) []string { | |
| var ips []string | |
| // split with ; | |
| for _,ipRange := range strings.Split(str, ";") { | |
| //expand with - | |
| var octets = strings.Split(strings.ReplaceAll(ipRange, " ", ""), ".") | |
| if len(octets) != 4 { | |
| fmt.Printf("Error: %v is invalid ipv4 value", ipRange) | |
| continue | |
| } | |
| var _octets [4][]string | |
| var _octetsInt [4][]int | |
| for i, octet := range octets { | |
| _octets[i] = strings.Split(octet, "-") | |
| } | |
| for i,_octet := range _octets { | |
| for _,_octet_e := range _octet { | |
| var _converted,_ = strconv.Atoi(_octet_e) | |
| _octetsInt[i] = append(_octetsInt[i], _converted) | |
| } | |
| if len(_octetsInt[i]) > 1 { | |
| min, max := MinMax(_octetsInt[i]) | |
| _octetsInt[i] = makeSeq(min,max) | |
| } | |
| } | |
| // combine ip address from octets | |
| for _,_octet1 := range _octetsInt[0] { | |
| for _,_octet2 := range _octetsInt[1] { | |
| for _,_octet3 := range _octetsInt[2] { | |
| for _,_octet4 := range _octetsInt[3] { | |
| ips = append(ips, fmt.Sprintf("%v.%v.%v.%v", _octet1, _octet2, _octet3, _octet4)) | |
| } | |
| } | |
| } | |
| } | |
| } | |
| return ips | |
| } | |
| func main() { | |
| // var testString = "10.255.250-251.40-45;10.255.250.32;10.255.250.21-22" | |
| // var testString = "10.250-252.250.40-45 ; 10.255.250.32; 10.255.250.21-22 " | |
| var testString = "10.250-252.250.40 - 45 ; 10.255.250.32; 10.255.250.21 -22 " | |
| var listIp []string | |
| listIp = parseString(testString) | |
| for _,ip := range listIp { | |
| fmt.Println(ip) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment