Skip to content

A Go Developer tool, Making use of goroutines and CLI framework Cobra

License

Notifications You must be signed in to change notification settings

ARCoder181105/netdiag

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

45 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

netdiag ๐ŸŒ

netdiag is a powerful, unified network diagnostic CLI tool built in Go. It combines the functionality of multiple network utilities (ping, traceroute, nmap, dig, whois, speedtest) into a single, fast, and easy-to-use command-line interface.

๐Ÿš€ Features

  • ๐Ÿ“ Concurrent Ping - Test connectivity to multiple hosts simultaneously
  • ๐Ÿ“ก Speed Test - Measure your internet download/upload speeds
  • ๐Ÿ—บ๏ธ Traceroute - Discover the network path to any destination
  • ๐Ÿ” Port Scanner - Scan for open TCP ports with high-performance concurrency
  • ๐ŸŒ HTTP Health Check - Verify website status and SSL certificate validity
  • ๐Ÿ“‹ DNS Lookup - Query DNS records (A, MX, TXT, NS, CNAME)
  • ๐Ÿ“– WHOIS Lookup - Retrieve domain registration information
  • ๐Ÿ”Ž Network Discovery - Scan your local network for active devices

๐Ÿ“‹ Table of Contents

๐Ÿ› ๏ธ Installation

Quick Install (Recommended)

Linux/macOS:

curl -fsSL https://raw.githubusercontent.com/ARCoder181105/netdiag/main/install.sh | bash

Windows (PowerShell as Administrator):

irm https://raw.githubusercontent.com/ARCoder181105/netdiag/main/install.ps1 | iex

Other Installation Methods

๐Ÿ“ฆ Package Managers

Homebrew (macOS/Linux)

brew tap ARCoder181105/netdiag
brew install netdiag

Go Install

go install github.com/ARCoder181105/netdiag@latest
โฌ‡๏ธ Download Pre-built Binaries

Download the latest release for your platform:

๐Ÿ“ฅ Download Latest Release

Available platforms:

  • Linux (amd64, arm64)
  • macOS (Intel, Apple Silicon)
  • Windows (amd64)

After downloading:

Linux/macOS:

chmod +x netdiag-*
sudo mv netdiag-* /usr/local/bin/netdiag

# Linux only: Grant ICMP capabilities
sudo setcap cap_net_raw+ep /usr/local/bin/netdiag

Windows:

  • Extract netdiag.exe
  • Move to C:\Windows\System32\ or add to PATH
๐Ÿ”จ Build from Source

Prerequisites:

  • Go 1.25 or higher
  • Git
# Clone repository
git clone https://github.com/ARCoder181105/netdiag.git
cd netdiag

# Build
go build -o netdiag

# Install (optional)
sudo mv netdiag /usr/local/bin/

# Linux: Grant ICMP capabilities
sudo setcap cap_net_raw+ep /usr/local/bin/netdiag

Verify Installation

netdiag --version
netdiag --help

Quick Test

# Test connectivity
netdiag ping google.com

# Run speed test
netdiag speedtest

# Scan ports
netdiag scan localhost -p 1-1000

๐Ÿ—‘๏ธ Uninstallation

If you need to remove netdiag, you can use the provided uninstallation scripts or remove it manually.

Quick Uninstall

Linux/macOS:

curl -fsSL https://raw.githubusercontent.com/ARCoder181105/netdiag/main/uninstall.sh | bash

Windows (PowerShell as Administrator):

irm https://raw.githubusercontent.com/ARCoder181105/netdiag/main/uninstall.ps1 | iex

Manual Uninstall

Removing netdiag from your system

If installed via Makefile or script:

# Using Makefile
make uninstall

# Or manually remove the binary
sudo rm /usr/local/bin/netdiag  # Linux/macOS

If installed via Homebrew:

brew uninstall netdiag
brew untap ARCoder181105/netdiag

If installed via Go:

rm $(go env GOPATH)/bin/netdiag

Windows:

# If installed to System32
Remove-Item C:\Windows\System32\netdiag.exe

# Or remove from your custom PATH location

๐Ÿš€ Quick Start

# Test connectivity to multiple hosts
netdiag ping google.com cloudflare.com

# Run an internet speed test
netdiag speedtest

# Trace the route to a destination
netdiag trace github.com

# Scan for open ports
netdiag scan 192.168.1.1 --ports 1-1024

# Check website health and SSL certificate
netdiag http https://example.com

# Lookup DNS records
netdiag dig google.com MX

# Get domain registration info
netdiag whois example.com

# Discover devices on your local network
netdiag discover

๐Ÿ“– Commands Reference

netdiag ping

Send ICMP echo requests to one or more hosts concurrently.

netdiag ping <host> [more hosts...]

Flags:
  -c, --count int       Number of ICMP packets to send (default: 3)
  -t, --timeout int     Timeout per packet in seconds (default: 1)
  -i, --interval int    Time to wait between packets in seconds (default: 1)

Examples:
  netdiag ping google.com
  netdiag ping -c 10 8.8.8.8 1.1.1.1

Output: Displays a table with packet loss, average/min/max latency for each host.


netdiag speedtest

Test your internet connection speed (download/upload).

netdiag speedtest

Flags:
  -u, --no-upload       Skip upload test
  -s, --server string   Specify server ID

Examples:
  netdiag speedtest
  netdiag speedtest --no-upload
  netdiag speedtest --server 12345

Output: Shows ISP info, server details, ping, download speed, and upload speed with quality assessment.


netdiag trace

Perform a traceroute to discover the network path to a destination.

netdiag trace <host>

Flags:
  -m, --max-hops int    Maximum number of hops (default: 30)

Examples:
  netdiag trace google.com
  netdiag trace 8.8.8.8 -m 20

Output: Displays each hop with IP address, hostname, and round-trip time.


netdiag scan

Scan a target host for open TCP ports using a high-performance worker pool.

netdiag scan <host>

Flags:
  -p, --ports string    Port range to scan (default: "1-1024")
  -t, --timeout int     Timeout in seconds (default: 1)

Examples:
  netdiag scan localhost
  netdiag scan 192.168.1.1 -p 80,443,8000-9000
  netdiag scan example.com -p 1-65535

Output: Lists all discovered open ports in a table format.


netdiag http

Check HTTP status and SSL certificate information for a website.

netdiag http <url>

Flags:
  -t, --timeout int     Timeout for the request in seconds (default: 5)
  -m, --method string   HTTP method (default: "GET")

Examples:
  netdiag http example.com
  netdiag http https://github.com
  netdiag http https://expired.badssl.com --timeout 10

Output:

  • HTTP status code (color-coded by result)
  • Request latency
  • SSL certificate details (subject, issuer, validity period, expiration warning)

netdiag dig

Perform DNS lookups for various record types.

netdiag dig <domain> [type]

Supported Types: A, MX, TXT, NS, CNAME

Examples:
  netdiag dig google.com          # Default: A records (IPv4)
  netdiag dig github.com MX       # Mail servers
  netdiag dig example.com TXT     # Text records
  netdiag dig google.com NS       # Name servers

Output: Table of DNS records matching the specified type.


netdiag whois

Retrieve domain registration and ownership information.

netdiag whois <domain>

Examples:
  netdiag whois google.com
  netdiag whois github.com

Output: Full WHOIS record including registrar, creation date, expiration date, and nameservers.


netdiag discover

Scan your local network for active devices using ping sweeps.

netdiag discover

Flags:
  -t, --timeout int     Ping timeout in milliseconds (default: 500)

Examples:
  netdiag discover
  netdiag discover -t 1000

Output:

  • Auto-detects your local IP range (e.g., 192.168.1.0/24)
  • Scans all 254 addresses
  • Displays table of discovered devices with IP, hostname, and latency

๐Ÿ—๏ธ Architecture & Concepts

Design Philosophy

netdiag is architected as an extensible platform, not just a collection of scripts. The modular design allows for easy addition of new diagnostic features without refactoring core functionality.

Key Technologies & Libraries

1. CLI Framework: Cobra

  • Library: github.com/spf13/cobra
  • Why: Industry-standard for complex CLI apps (used by Kubernetes, Hugo, GitHub CLI)
  • Benefits:
    • Powerful nested subcommand support
    • Robust flag parsing
    • Auto-generated help text
    • Easy integration with configuration files via Viper

2. Concurrency Management: errgroup

  • Library: golang.org/x/sync/errgroup
  • Why: Professional error handling for concurrent operations
  • Benefits:
    • Automatic error propagation from goroutines
    • Context cancellation on first error
    • Built-in concurrency limiting with SetLimit()
    • Prevents resource exhaustion

Example Use Case: When pinging 100 hosts, errgroup limits concurrent operations to 20, preventing system overload while efficiently managing errors.

3. ICMP Operations: pro-bing

  • Library: github.com/prometheus-community/pro-bing
  • Why: Production-grade ICMP library from Prometheus community
  • Features:
    • Detailed statistics (min/max/avg RTT, packet loss, jitter)
    • Privileged and unprivileged mode support
    • Callback-based result handling

4. Output Formatting

Table Rendering: github.com/olekukonko/tablewriter

  • Transforms raw data into clean, aligned ASCII tables
  • Automatic column width calculation
  • Border customization

Semantic Colors: github.com/fatih/color

  • Cross-platform color support
  • Semantic color scheme:
    • ๐ŸŸข Green: Success (host up, port open, SSL valid)
    • ๐Ÿ”ด Red: Failure (host down, connection refused, SSL expired)
    • ๐ŸŸก Yellow: Warning (high latency, SSL expiring soon)
    • ๐Ÿ”ต Cyan: Informational (headers, progress updates)

5. Network Operations

  • Port Scanning: Go's net.DialTimeout() with semaphore-based concurrency control
  • Traceroute: Raw ICMP sockets via golang.org/x/net/icmp with TTL manipulation
  • DNS Queries: Go's standard net package for DNS lookups
  • WHOIS: github.com/likexian/whois
  • Speed Test: github.com/showwin/speedtest-go

Concurrency Patterns

Worker Pool with Semaphore (Port Scanner)

semaphore := make(chan struct{}, 100) // Limit to 100 concurrent scans

for _, port := range ports {
    wg.Add(1)
    go func(p int) {
        defer wg.Done()
        
        semaphore <- struct{}{}        // Acquire slot (blocks if full)
        defer func() { <-semaphore }() // Release slot
        
        // Perform scan
        conn, err := net.DialTimeout("tcp", address, timeout)
        if err == nil {
            conn.Close()
            results <- p // Port is open
        }
    }(port)
}

Benefits: Prevents "too many open files" errors while maximizing throughput.

errgroup Pattern (Concurrent Ping)

group, ctx := errgroup.WithContext(context.Background())
group.SetLimit(20) // Max 20 concurrent pings

for _, host := range hosts {
    h := host
    group.Go(func() error {
        if ctx.Err() != nil {
            return ctx.Err() // Stop if another goroutine failed
        }
        
        pinger, err := probing.NewPinger(h)
        if err != nil {
            return err // Error propagates, cancels context
        }
        
        return pinger.Run()
    })
}

if err := group.Wait(); err != nil {
    // Handle first error from any goroutine
}

Benefits: Automatic error handling, context cancellation, and controlled concurrency.

Raw Socket Operations & Privileges

Many network diagnostic operations (ping, traceroute) require raw socket access to craft custom ICMP packets. This is a privileged operation for security reasons.

The Problem

  • Raw sockets allow packet crafting, which could be used maliciously
  • Operating systems restrict this capability to root/Administrator

The Solution: Linux Capabilities

Instead of running the entire program as root (sudo netdiag), grant only the specific capability needed:

sudo setcap cap_net_raw+ep /usr/local/bin/netdiag

This grants CAP_NET_RAW (raw socket creation) to the binary while keeping everything else unprivilegedโ€”following the principle of least privilege.


๐Ÿ” Permissions

Linux/macOS

After installation, grant ICMP capabilities:

sudo setcap cap_net_raw+ep /usr/local/bin/netdiag

Alternatively, run with sudo (not recommended):

sudo netdiag ping google.com

Windows

Run Command Prompt or PowerShell as Administrator for full functionality.


๐Ÿค Contributing

Contributions are welcome! Here are some ideas for enhancements:

  • MTR (My Traceroute) implementation for continuous latency monitoring
  • IP geolocation lookup
  • mDNS/Zeroconf service discovery
  • JSON output mode (--json flag)
  • Configuration file support
  • IPv6 support for all commands

Development Setup

# Clone the repo
git clone https://github.com/ARCoder181105/netdiag.git
cd netdiag

# Install dependencies
go mod download

# Run tests
go test ./...

# Build
go build -o netdiag

Submitting Changes

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.


๐Ÿ™ Acknowledgments

Built with these excellent Go libraries:


๐Ÿ“ž Support

For issues, questions, or feature requests, please open an issue.


Made with โค๏ธ by ARCoder181105

About

A Go Developer tool, Making use of goroutines and CLI framework Cobra

Resources

License

Contributing

Stars

Watchers

Forks

Packages

No packages published

Contributors 2

  •  
  •