SoFunction
Updated on 2025-03-04

How to golang concurrent ping host

Taking advantage of golang's good support for high concurrency, write one ip line to a file in the same directory.

In fact, this function can be done with just one command in Linux:

cat | xargs -P 10 -I {} ping -fc 100 {}

package main

import (
  "bufio"
  "bytes"
  "fmt"
  "io"
  "io/ioutil"
  "log"
  "os"
  "os/exec"
  "strings"
  "sync"
  "runtime"
)

func RunCMD(command string) string {
  in := (nil)
  cmd := ("sh")
   = in
  (command + "\n")
  stdout, err := ()
  if err != nil {
    (err)
  }
  defer ()
  if err := (); err != nil {
    (err)
  }
  opBytes, err := (stdout)
  if err != nil {
    (err)
  }
  return string(opBytes)
}

func ping(ip string) string {
  cmd := "ping -fc 100 " + ip
  return RunCMD(cmd)
}

var ips = []string{}

func main() {
  (())
  fileName := ""
  f, err := (fileName)
  if err != nil {
    (err)
  }
  buf := (f)
  for {
    line, err := ('\n')
    line = (line)
    if err != nil {
      if err ==  {
        //("File read over!")
        break
      }
      (err)
    }
    ips = append(ips, line)
  }
  wg := &{}
  ch := make(chan string, len(ips))
  //(ips)
  for i:= 0; i < len(ips); i++ {
    (1)
    go func(i int) {
      ch <- ping(ips[i])
      ()
    }(i)
  }
  ()

  //(len(ch))
  for i := 0; i < len(ips); i++ {
    (<-ch)
  }
}

The above method of golang concurrent ping host is all the content I share with you. I hope you can give you a reference and I hope you can support me more.