Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
*.dll
*.so
*.dylib
subping

# Test binary, built with `go test -c`
*.test
Expand Down Expand Up @@ -136,3 +137,9 @@ fabric.properties

### Solarscanner
.scannerwork/*

### Custom agents workspace
AGENTS.md
CLAUDE.md
ISSUES.md
issue-*.md
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ The following flags are available for the `subping` command:
- `-i, --interval string`: Specifies the time duration between each ping request. (default "300ms")
- `-n, --job int`: Specifies the number of maximum concurrent jobs spawned to perform ping operations. (default 128)
- `--offline`: Specify whether to display the list of offline hosts.
- `-t, --timeout string`: Specifies the maximum ping timeout duration for each ping request. (default "80ms")
- `-t, --timeout string`: Specifies the maximum ping timeout duration for each ping request. (default "1s")
- `-v, --version`: Displays the version information for `subping`.

## Examples
Expand Down
116 changes: 68 additions & 48 deletions cmd/subping/main.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
package main

import (
"bytes"
"fmt"
"log"
"net"
"sort"
"time"

"github.com/common-nighthawk/go-figure"
"github.com/fadhilyori/subping"
"github.com/fadhilyori/subping/internal/display"
"github.com/spf13/cobra"
)

Expand All @@ -20,6 +18,7 @@ var (
pingMaxWorkers int
subpingVersion = "dev"
showOfflineHostList bool
sortBy string
)

func main() {
Expand All @@ -29,11 +28,12 @@ func main() {
Short: "A tool for pinging IP addresses in a subnet",
Long: "Subping is a command-line tool that allows you to ping IP addresses within a specified subnet range.",
Args: cobra.MatchAll(cobra.ExactArgs(1), cobra.OnlyValidArgs),
Run: runSubping,
Run: func(cmd *cobra.Command, args []string) {
runSubping(cmd, args)
},
PreRun: func(cmd *cobra.Command, args []string) {
figure.NewFigure("subping", "larry3d", true).Print()
fmt.Println(cmd.Version)
fmt.Print("\n\n")
fmt.Print("\n")
},
}

Expand All @@ -55,13 +55,16 @@ func main() {
flags.BoolVar(&showOfflineHostList, "offline", false,
"Specify whether to display the list of offline hosts.",
)
flags.StringVar(&sortBy, "sort", "ip",
"Sort results by: ip, latency, loss, jitter (default: ip)",
)

if err := rootCmd.Execute(); err != nil {
log.Fatal(err)
}
}

func runSubping(_ *cobra.Command, args []string) {
func runSubping(rootCmd *cobra.Command, args []string) {
subnetString := args[0]

startTime := time.Now()
Expand All @@ -76,75 +79,92 @@ func runSubping(_ *cobra.Command, args []string) {
log.Fatalf("Invalid interval format '%s': %v\nValid examples: 300ms, 1s, 2s", pingIntervalStr, err)
}

sortOption := display.SortByIP
switch sortBy {
case "latency":
sortOption = display.SortByLatency
case "loss":
sortOption = display.SortByLoss
case "jitter":
sortOption = display.SortByJitter
case "ip":
sortOption = display.SortByIP
default:
log.Fatalf("Invalid sort option '%s'. Valid options: ip, latency, loss, jitter", sortBy)
}

displayConfig := display.DisplayConfig{
EnabledColors: true,
EnabledProgress: true,
SortBy: sortOption,
UseEnhancedHealthScore: true,
}

d := display.NewDisplay(displayConfig)

s, err := subping.NewSubping(&subping.Options{
Subnet: subnetString,
Count: pingCount,
Interval: pingInterval,
Timeout: pingTimeout,
MaxWorkers: pingMaxWorkers,
LogLevel: "error",
ProgressCallback: func(current, total int, currentIP string, onlineCount int) {
d.UpdateProgress(current, total, currentIP, onlineCount)
},
})
if err != nil {
log.Fatal(err.Error())
}

fmt.Printf("Network : %s\n", s.TargetsIterator.IPNet.String())
fmt.Printf("IP Ranges : %s - %s\n",
s.TargetsIterator.FirstIP.String(), s.TargetsIterator.LastIP.String(),
d.ShowHeader(
s.TargetsIterator.IPNet.String(),
fmt.Sprintf("%s - %s", s.TargetsIterator.FirstIP.String(), s.TargetsIterator.LastIP.String()),
s.TargetsIterator.TotalHosts,
s.MaxWorkers,
s.Count,
s.Interval.String(),
pingTimeoutStr,
rootCmd.Version,
)
fmt.Printf("Total hosts : %d\n", s.TargetsIterator.TotalHosts)
fmt.Printf("Total workers : %d\n", s.MaxWorkers)
fmt.Printf("Count : %d\n", s.Count)
fmt.Printf("Interval : %s\n", s.Interval.String())
fmt.Printf("Timeout : %s\n", pingTimeoutStr)
fmt.Println(`-------------------------------------------------------------------------------`)
fmt.Printf("| %-39s | %-16s | %-14s |\n", "IP Address", "Avg Latency", "Packet Loss")
fmt.Println(`-------------------------------------------------------------------------------`)

s.Run()

results, totalHostOnline := s.GetOnlineHosts()
onlineResults, totalHostOnline := s.GetOnlineHosts()

// Extract keys into a slice
keys := make([]net.IP, 0, len(results))
for key := range results {
keys = append(keys, net.ParseIP(key))
// Calculate proper capacity based on what we'll actually store
var estimatedCapacity int
if showOfflineHostList {
estimatedCapacity = s.TargetsIterator.TotalHosts // All hosts (online + offline)
} else {
estimatedCapacity = totalHostOnline // Only online hosts
}

// Sort the keys Based on byte comparison
sort.Slice(keys, func(i, j int) bool {
return bytes.Compare(keys[i].To16(), keys[j].To16()) < 0
})

for _, ip := range keys {
// convert bytes to string in each line of IP
ipString := ip.String()
stats := results[ipString]
packetLossPercentageStr := fmt.Sprintf("%.2f %%", stats.PacketLoss)
allResults := make([]display.HostResult, 0, estimatedCapacity)

fmt.Printf(
"| %-39s | %-16s | %-14s |\n",
ipString, stats.AvgRtt.String(), packetLossPercentageStr)
for ip, result := range onlineResults {
allResults = append(allResults, display.ConvertPingResult(ip, result))
}

fmt.Println(`-------------------------------------------------------------------------------`)

if showOfflineHostList {
fmt.Println("\nOffline hosts :")
for ip, stats := range s.Results {
if stats.PacketsRecv == 0 {
fmt.Printf(
" - %s\t(Loss: %s, Latency: %s)\n",
ip, fmt.Sprintf("%.2f %%", stats.PacketLoss), stats.AvgRtt.String(),
)
for ip, result := range s.Results {
if result.PacketsRecv == 0 {
allResults = append(allResults, display.ConvertPingResult(ip, result))
}
}
}

d.ShowResults(allResults)

elapsed := time.Since(startTime)
totalHostOffline := s.TargetsIterator.TotalHosts - totalHostOnline

fmt.Printf("\nTotal Hosts Online : %d\n", totalHostOnline)
fmt.Printf("Total Hosts Offline : %d\n", totalHostOffline)
fmt.Printf("Execution time : %s\n\n", elapsed.String())
var scanRate float64
if elapsed.Seconds() > 0 {
scanRate = float64(s.TargetsIterator.TotalHosts) / elapsed.Seconds()
}

d.ShowSummary(s.TargetsIterator.TotalHosts, totalHostOnline, totalHostOffline, elapsed, scanRate)
}

// Avoid to ping with 0.0.0.0/0
15 changes: 15 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,31 @@ toolchain go1.24.4

require (
github.com/common-nighthawk/go-figure v0.0.0-20210622060536-734e95fb86be
github.com/fatih/color v1.18.0
github.com/olekukonko/tablewriter v1.1.2
github.com/prometheus-community/pro-bing v0.7.0
github.com/schollz/progressbar/v3 v3.19.0
github.com/sirupsen/logrus v1.9.3
github.com/spf13/cobra v1.10.2
)

require (
github.com/clipperhouse/displaywidth v0.6.0 // indirect
github.com/clipperhouse/stringish v0.1.1 // indirect
github.com/clipperhouse/uax29/v2 v2.3.0 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-runewidth v0.0.19 // indirect
github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db // indirect
github.com/olekukonko/cat v0.0.0-20250911104152-50322a0618f6 // indirect
github.com/olekukonko/errors v1.1.0 // indirect
github.com/olekukonko/ll v0.1.3 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
github.com/spf13/pflag v1.0.10 // indirect
golang.org/x/net v0.48.0 // indirect
golang.org/x/sync v0.19.0 // indirect
golang.org/x/sys v0.39.0 // indirect
golang.org/x/term v0.38.0 // indirect
)
41 changes: 39 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,18 +1,49 @@
github.com/chengxilo/virtualterm v1.0.4 h1:Z6IpERbRVlfB8WkOmtbHiDbBANU7cimRIof7mk9/PwM=
github.com/chengxilo/virtualterm v1.0.4/go.mod h1:DyxxBZz/x1iqJjFxTFcr6/x+jSpqN0iwWCOK1q10rlY=
github.com/clipperhouse/displaywidth v0.6.0 h1:k32vueaksef9WIKCNcoqRNyKbyvkvkysNYnAWz2fN4s=
github.com/clipperhouse/displaywidth v0.6.0/go.mod h1:R+kHuzaYWFkTm7xoMmK1lFydbci4X2CicfbGstSGg0o=
github.com/clipperhouse/stringish v0.1.1 h1:+NSqMOr3GR6k1FdRhhnXrLfztGzuG+VuFDfatpWHKCs=
github.com/clipperhouse/stringish v0.1.1/go.mod h1:v/WhFtE1q0ovMta2+m+UbpZ+2/HEXNWYXQgCt4hdOzA=
github.com/clipperhouse/uax29/v2 v2.3.0 h1:SNdx9DVUqMoBuBoW3iLOj4FQv3dN5mDtuqwuhIGpJy4=
github.com/clipperhouse/uax29/v2 v2.3.0/go.mod h1:Wn1g7MK6OoeDT0vL+Q0SQLDz/KpfsVRgg6W7ihQeh4g=
github.com/common-nighthawk/go-figure v0.0.0-20210622060536-734e95fb86be h1:J5BL2kskAlV9ckgEsNQXscjIaLiOYiZ75d4e94E6dcQ=
github.com/common-nighthawk/go-figure v0.0.0-20210622060536-734e95fb86be/go.mod h1:mk5IQ+Y0ZeO87b858TlA645sVcEcbiX6YqP98kt+7+w=
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM=
github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-runewidth v0.0.19 h1:v++JhqYnZuu5jSKrk9RbgF5v4CGUjqRfBm05byFGLdw=
github.com/mattn/go-runewidth v0.0.19/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=
github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db h1:62I3jR2EmQ4l5rM/4FEfDWcRD+abF5XlKShorW5LRoQ=
github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db/go.mod h1:l0dey0ia/Uv7NcFFVbCLtqEBQbrT4OCwCSKTEv6enCw=
github.com/olekukonko/cat v0.0.0-20250911104152-50322a0618f6 h1:zrbMGy9YXpIeTnGj4EljqMiZsIcE09mmF8XsD5AYOJc=
github.com/olekukonko/cat v0.0.0-20250911104152-50322a0618f6/go.mod h1:rEKTHC9roVVicUIfZK7DYrdIoM0EOr8mK1Hj5s3JjH0=
github.com/olekukonko/errors v1.1.0 h1:RNuGIh15QdDenh+hNvKrJkmxxjV4hcS50Db478Ou5sM=
github.com/olekukonko/errors v1.1.0/go.mod h1:ppzxA5jBKcO1vIpCXQ9ZqgDh8iwODz6OXIGKU8r5m4Y=
github.com/olekukonko/ll v0.1.3 h1:sV2jrhQGq5B3W0nENUISCR6azIPf7UBUpVq0x/y70Fg=
github.com/olekukonko/ll v0.1.3/go.mod h1:b52bVQRRPObe+yyBl0TxNfhesL0nedD4Cht0/zx55Ew=
github.com/olekukonko/tablewriter v1.1.2 h1:L2kI1Y5tZBct/O/TyZK1zIE9GlBj/TVs+AY5tZDCDSc=
github.com/olekukonko/tablewriter v1.1.2/go.mod h1:z7SYPugVqGVavWoA2sGsFIoOVNmEHxUAAMrhXONtfkg=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/prometheus-community/pro-bing v0.7.0 h1:KFYFbxC2f2Fp6c+TyxbCOEarf7rbnzr9Gw8eIb0RfZA=
github.com/prometheus-community/pro-bing v0.7.0/go.mod h1:Moob9dvlY50Bfq6i88xIwfyw7xLFHH69LUgx9n5zqCE=
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/schollz/progressbar/v3 v3.19.0 h1:Ea18xuIRQXLAUidVDox3AbwfUhD0/1IvohyTutOIFoc=
github.com/schollz/progressbar/v3 v3.19.0/go.mod h1:IsO3lpbaGuzh8zIMzgY3+J8l4C8GjO0Y9S69eFvNsec=
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
Expand All @@ -21,16 +52,22 @@ github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An
github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=
github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU=
golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY=
golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/term v0.38.0 h1:PQ5pkm/rLO6HnxFR7N2lJHOZX6Kez5Y1gDSJla6jo7Q=
golang.org/x/term v0.38.0/go.mod h1:bSEAKrOT1W+VSu9TSCMtoGEOUcKxOKgl3LE5QEF/xVg=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
25 changes: 25 additions & 0 deletions internal/config/logger.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// Package config provides global configuration for the subping application
package config

import (
"github.com/sirupsen/logrus"
"os"
)

func init() {
level := os.Getenv("SUBPING_LOG_LEVEL")
if level == "" {
level = "error" // Default level
}

if parsedLevel, err := logrus.ParseLevel(level); err == nil {
logrus.SetLevel(parsedLevel)
} else {
logrus.SetLevel(logrus.ErrorLevel) // Fallback to error
}
}

// GetLogLevel returns the current global log level
func GetLogLevel() logrus.Level {
return logrus.GetLevel()
}
Loading