package test
import (
"fmt"
"net"
"testing"
)
func Cidr(cidr string) ([]string, error) {
ip, ipnet, err := net.ParseCIDR(cidr)
if err != nil {
return nil, err
}
var ips []string
for ip := ip.Mask(ipnet.Mask); ipnet.Contains(ip); inc(ip) {
ips = append(ips, ip.String())
}
return ips[1 : len(ips)-1], nil
}
func inc(ip net.IP) {
for j := len(ip) - 1; j >= 0; j-- {
ip[j]++
if ip[j] > 0 {
break
}
}
}
func TestCird(t *testing.T) {
hosts, _ := Cidr("192.168.11.0/20")
for _, ip := range hosts {
fmt.Println("sent: " + ip)
}
}
Last active
April 2, 2020 05:37
-
-
Save dollarkillerx/b0033f948a875dc220760ec691f7ccb8 to your computer and use it in GitHub Desktop.
golang 生成IP列表
package test
import (
"bytes"
"encoding/binary"
"fmt"
"log"
"net"
"strconv"
"testing"
)
//ip到数字
func ip2Long(ip string) uint32 {
var long uint32
binary.Read(bytes.NewBuffer(net.ParseIP(ip).To4()), binary.BigEndian, &long)
return long
}
//数字到IP
func backtoIP4(ipInt int64) string {
// need to do two bit shifting and “0xff” masking
b0 := strconv.FormatInt((ipInt>>24)&0xff, 10)
b1 := strconv.FormatInt((ipInt>>16)&0xff, 10)
b2 := strconv.FormatInt((ipInt>>8)&0xff, 10)
b3 := strconv.FormatInt((ipInt & 0xff), 10)
return b0 + "." + b1 + "." + b2 + "." + b3
}
func RangeIP(start,end string) ([]string,error) {
result := make([]string,0)
ip1 := ip2Long(start)
ip2 := ip2Long(end)
for i := ip1; i <= ip2; i++ {
i := int64(i)
result = append(result,backtoIP4(i))
}
return result,nil
}
func TestRangeIP(t *testing.T) {
ip, err := RangeIP("221.177.0.0", "221.177.7.255")
if err != nil {
log.Fatalln(err)
}
fmt.Println(ip)
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment