-
-
Save liushuainudt/46e3ed8893e516044e34769c9d89ddc9 to your computer and use it in GitHub Desktop.
get all IP address from CIDR in golang
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" | |
| "net" | |
| "os/exec" | |
| "sync" | |
| "github.com/k0kubun/pp" | |
| ) | |
| func Hosts(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()) | |
| } | |
| // Remove network address and broadcast address | |
| 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 | |
| } | |
| } | |
| } | |
| type Pong struct { | |
| Ip string | |
| Alive bool | |
| } | |
| func ping(ip string, wg *sync.WaitGroup, pongChan chan<- Pong) { | |
| defer wg.Done() | |
| _, err := exec.Command("ping", "-c1", "-t1", ip).Output() | |
| alive := err == nil | |
| pongChan <- Pong{Ip: ip, Alive: alive} | |
| } | |
| func main() { | |
| hosts, err := Hosts("192.168.11.0/24") | |
| if err != nil { | |
| fmt.Println(err) | |
| return | |
| } | |
| var wg sync.WaitGroup | |
| pongChan := make(chan Pong, len(hosts)) | |
| var alives []Pong | |
| wg.Add(len(hosts)) | |
| for _, ip := range hosts { | |
| go ping(ip, &wg, pongChan) | |
| } | |
| go func() { | |
| wg.Wait() | |
| close(pongChan) | |
| }() | |
| for pong := range pongChan { | |
| if pong.Alive { | |
| alives = append(alives, pong) | |
| } | |
| } | |
| pp.Println(alives) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment