-
-
Save peakle/cd712b72a611f481fc3d07cc1a1f864b to your computer and use it in GitHub Desktop.
ping 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" | |
| "sync" | |
| "time" | |
| ) | |
| func Hosts(cidr string) ([]string, error) { | |
| ip, ipnet, err := net.ParseCIDR(cidr) | |
| if err != nil { | |
| return nil, err | |
| } | |
| var ips []string | |
| for i := ip.Mask(ipnet.Mask); ipnet.Contains(i); inc(i) { | |
| ips = append(ips, i.String()) | |
| } | |
| return ips, 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, pongChan chan<- Pong) { | |
| _, err := net.DialTimeout("tcp", ip+":80", 3*time.Second) | |
| var alive bool | |
| if err != nil { | |
| alive = false | |
| } else { | |
| alive = true | |
| } | |
| pongChan <- Pong{Ip: ip, Alive: alive} | |
| } | |
| func receivePong(pongNum int, pongChan <-chan Pong, doneChan chan<- []Pong, wg *sync.WaitGroup) { | |
| var alives []Pong | |
| for i := 0; i < pongNum; i++ { | |
| select { | |
| case pong := <-pongChan: | |
| // fmt.Println("received:", pong) | |
| if pong.Alive { | |
| alives = append(alives, pong) | |
| } | |
| } | |
| wg.Done() | |
| } | |
| doneChan <- alives | |
| } | |
| func main() { | |
| hosts, _ := Hosts("192.168.1.0/24") | |
| pongChan := make(chan Pong, len(hosts)) | |
| doneChan := make(chan []Pong) | |
| var wg sync.WaitGroup | |
| wg.Add(len(hosts)) | |
| for _, ip := range hosts { | |
| go ping(ip, pongChan) | |
| // fmt.Println("sent: " + ip) | |
| } | |
| go receivePong(len(hosts), pongChan, doneChan, &wg) | |
| wg.Wait() | |
| alives := <-doneChan | |
| fmt.Println(alives) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment