forked from bauljamic123arlijam/neko-u-krovu-bot
initial commit
This commit is contained in:
68
ping/ping.go
Normal file
68
ping/ping.go
Normal file
@@ -0,0 +1,68 @@
|
||||
package ping
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"os/exec"
|
||||
"sync"
|
||||
)
|
||||
|
||||
func Run() int {
|
||||
localIP, err := getLocalIP()
|
||||
if err != nil {
|
||||
fmt.Println("Error getting local IP:", err)
|
||||
return 0
|
||||
}
|
||||
|
||||
network := getNetworkPrefix(localIP)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
deviceCount := 0
|
||||
mu := &sync.Mutex{}
|
||||
|
||||
for i := 1; i < 255; i++ {
|
||||
wg.Add(1)
|
||||
go func(i int) {
|
||||
defer wg.Done()
|
||||
addr := fmt.Sprintf("%s.%d", network[:len(network)-2], i)
|
||||
|
||||
if ping(addr) {
|
||||
mu.Lock()
|
||||
deviceCount++
|
||||
mu.Unlock()
|
||||
}
|
||||
}(i)
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
return deviceCount
|
||||
}
|
||||
|
||||
func getLocalIP() (net.IP, error) {
|
||||
addrs, err := net.InterfaceAddrs()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, addr := range addrs {
|
||||
if ipnet, ok := addr.(*net.IPNet); ok && ipnet.IP.IsGlobalUnicast() {
|
||||
return ipnet.IP, nil
|
||||
}
|
||||
}
|
||||
return nil, fmt.Errorf("local IP not found")
|
||||
}
|
||||
|
||||
func getNetworkPrefix(ip net.IP) string {
|
||||
ip = ip.To4()
|
||||
return fmt.Sprintf("%d.%d.%d.0", ip[0], ip[1], ip[2])
|
||||
}
|
||||
|
||||
|
||||
func ping(ip string) bool {
|
||||
output, err := exec.Command("ping", "-c", "1", "-W", "1", ip).CombinedOutput()
|
||||
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
_ = output
|
||||
return true
|
||||
}
|
Reference in New Issue
Block a user