Tag: #Networking

  • DNS Ping Test Utility PowerShell Script

    This PowerShell script allows users to select from a list of popular DNS servers and perform customizable ping tests to verify network connectivity. It supports both continuous and fixed-count pings, configurable intervals, optional logging, and displays summary statistics for comprehensive network diagnostics.

    Click to view script…
    <#
    .SYNOPSIS
        DNS Ping Test Utility
    
    .DESCRIPTION
        This script allows the user to choose from a list of popular DNS servers (e.g., Google, Cloudflare, OpenDNS, etc.)
        and then performs either continuous or fixed-count ping tests to verify network connectivity.
        Users can configure the interval between pings and optionally log the results to a file for further analysis.
        
    .NOTES
        Press Ctrl+C to exit continuous ping mode.
    #>
    
    # Define a list of DNS providers.
    $dnsProviders = @(
        [PSCustomObject]@{Name="Google DNS";       IP="8.8.8.8"},
        [PSCustomObject]@{Name="Cloudflare DNS";   IP="1.1.1.1"},
        [PSCustomObject]@{Name="OpenDNS";          IP="208.67.222.222"},
        [PSCustomObject]@{Name="Quad9 DNS";        IP="9.9.9.9"},
        [PSCustomObject]@{Name="Level3 DNS";       IP="4.2.2.2"}
    )
    
    # Display the DNS server options.
    Write-Host "Select a DNS server to ping:" -ForegroundColor Cyan
    for ($i = 0; $i -lt $dnsProviders.Count; $i++) {
        Write-Host ("{0}. {1} ({2})" -f ($i + 1), $dnsProviders[$i].Name, $dnsProviders[$i].IP)
    }
    
    # Prompt the user to choose a DNS server.
    [int]$choice = Read-Host "Enter the number corresponding to your choice"
    if ($choice -lt 1 -or $choice -gt $dnsProviders.Count) {
        Write-Error "Invalid selection. Exiting."
        exit
    }
    
    $selectedDNS = $dnsProviders[$choice - 1]
    Write-Host "You selected: $($selectedDNS.Name) ($($selectedDNS.IP))" -ForegroundColor Green
    
    # Ask if the user wants a fixed number of pings or continuous ping.
    $pingCountInput = Read-Host "Enter number of pings (or press Enter for continuous ping)"
    if ($pingCountInput -match '^\d+$') {
        $pingCount = [int]$pingCountInput
        $isContinuous = $false
    } else {
        $isContinuous = $true
    }
    
    # Ask for the interval between pings in seconds.
    $intervalInput = Read-Host "Enter interval in seconds between pings (default is 1 second)"
    if ([string]::IsNullOrWhiteSpace($intervalInput)) {
        $interval = 1
    } else {
        $interval = [double]$intervalInput
    }
    
    # Ask if the user wants to log the results to a file.
    $logChoice = Read-Host "Do you want to log results to a file? (Y/N)"
    $logEnabled = $false
    if ($logChoice -match '^[Yy]') {
        $logEnabled = $true
        $logFile = Read-Host "Enter log file path (or press Enter for default 'DNSPingLog.txt')"
        if ([string]::IsNullOrWhiteSpace($logFile)) {
            $logFile = "DNSPingLog.txt"
        }
        Write-Host "Logging enabled. Results will be saved to $logFile" -ForegroundColor Green
    }
    
    # Initialize an array to store successful ping response times if a fixed ping count is specified.
    if (-not $isContinuous) {
        $results = @()
    }
    
    Write-Host "Starting ping test to $($selectedDNS.IP)..." -ForegroundColor Cyan
    
    # Function to log output if logging is enabled.
    function Log-Output {
        param (
            [string]$message
        )
        if ($logEnabled) {
            $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
            Add-Content -Path $logFile -Value "[$timestamp] $message"
        }
    }
    
    # Run the ping test.
    if ($isContinuous) {
        Write-Host "Press Ctrl+C to stop continuous ping."
        while ($true) {
            try {
                $pingResult = Test-Connection -ComputerName $selectedDNS.IP -Count 1 -ErrorAction SilentlyContinue
                $timestamp = Get-Date -Format "HH:mm:ss"
                if ($pingResult) {
                    $replyTime = $pingResult.ResponseTime
                    $output = "[$timestamp] Ping $($i)/$($pingCount): Reply from $($selectedDNS.IP): time = $replyTime ms"
                } else {
                    $output = "[$timestamp] Ping $($i)/$($pingCount): Request timed out for $($selectedDNS.IP)."
                }
                Write-Host $output
                Log-Output -message $output
            }
            catch {
                Write-Host "An error occurred: $_"
                Log-Output -message "Error: $_"
            }
            Start-Sleep -Seconds $interval
        }
    } else {
        for ($i = 1; $i -le $pingCount; $i++) {
            try {
                $pingResult = Test-Connection -ComputerName $selectedDNS.IP -Count 1 -ErrorAction SilentlyContinue
                $timestamp = Get-Date -Format "HH:mm:ss"
                if ($pingResult) {
                    $replyTime = $pingResult.ResponseTime
                    $output = "[$timestamp] Ping $($i)/$($pingCount): Reply from $($selectedDNS.IP): time = $replyTime ms"
                    $results += $replyTime
                } else {
                    $output = "[$timestamp] Ping $($i)/$($pingCount): Request timed out for $($selectedDNS.IP)."
                }
                Write-Host $output
                Log-Output -message $output
            }
            catch {
                Write-Host "An error occurred: $_"
                Log-Output -message "Error: $_"
            }
            Start-Sleep -Seconds $interval
        }
        
        # Provide summary statistics for the fixed-count ping test.
        if ($results.Count -gt 0) {
            $avgTime = [Math]::Round(($results | Measure-Object -Average).Average, 2)
            Write-Host "`nPing test completed. Average response time: $avgTime ms" -ForegroundColor Green
            Log-Output -message "Ping test completed. Average response time: $avgTime ms"
        } else {
            Write-Host "`nPing test completed. No successful pings." -ForegroundColor Yellow
            Log-Output -message "Ping test completed. No successful pings."
        }
    }
  • Check Public IP with PowerShell Script

    A straightforward PowerShell script that lets you quickly determine your current public IP address in a simple and hassle-free way.

    Click to view script…
    # Get-PublicIP.ps1
    # This script retrieves and displays your public IP address
    
    # Query the API to get your public IP address in JSON format.
    $response = Invoke-RestMethod -Uri "https://api.ipify.org?format=json"
    
    # Display the IP address.
    Write-Host "Your public IP address is: $($response.ip)"

  • Retrieve Detailed Windows Network Information with PowerShell

    This PowerShell script gathers comprehensive network details from your Windows machine—including default route, local IP, subnet mask, broadcast address, MAC address, DNS servers, and public IP—while also performing a ping test to 8.8.8.8 for latency analysis. It’s a handy tool for troubleshooting and monitoring your network.

    Click to view script…
    # NetworkInfoDetailed.ps1 - Detailed network information for Windows
    
    # Helper function: Convert a CIDR prefix (e.g. 24) to a dotted-decimal subnet mask (e.g. 255.255.255.0)
    function Convert-PrefixToSubnetMask {
        param (
            [int]$PrefixLength
        )
        $max = [uint32]::MaxValue
        # For a given prefix, the netmask is: netmask = max - (2^(32 - prefix) - 1)
        $netmaskInt = $max - ([uint32]([math]::Pow(2, (32 - $PrefixLength)) - 1))
        $octet1 = ($netmaskInt -shr 24) -band 0xFF
        $octet2 = ($netmaskInt -shr 16) -band 0xFF
        $octet3 = ($netmaskInt -shr 8) -band 0xFF
        $octet4 = $netmaskInt -band 0xFF
        return "$octet1.$octet2.$octet3.$octet4"
    }
    
    # Helper function: Convert an IP string to a 32-bit unsigned integer.
    function Convert-IPStringToInt {
        param ([string]$ip)
        $bytes = $ip.Split('.') | ForEach-Object { [uint32]$_ }
        return ([uint32]($bytes[0] -shl 24)) -bor ([uint32]($bytes[1] -shl 16)) -bor ([uint32]($bytes[2] -shl 8)) -bor $bytes[3]
    }
    
    # Helper function: Convert a 32-bit unsigned integer to an IP string.
    function Convert-IntToIPAddress {
        param ([uint32]$ipInt)
        $a = ($ipInt -shr 24) -band 0xFF
        $b = ($ipInt -shr 16) -band 0xFF
        $c = ($ipInt -shr 8) -band 0xFF
        $d = $ipInt -band 0xFF
        return "$a.$b.$c.$d"
    }
    
    # Begin output with colored text using Write-Host.
    Write-Host "Gathering default route information..." -ForegroundColor Blue
    
    # Get the default route (DestinationPrefix "0.0.0.0/0") for IPv4.
    $defaultRoute = Get-NetRoute -DestinationPrefix "0.0.0.0/0" -ErrorAction SilentlyContinue | 
        Where-Object { $_.NextHop -ne "0.0.0.0" } | 
        Sort-Object -Property RouteMetric | 
        Select-Object -First 1
    
    if (-not $defaultRoute) {
        Write-Host "Error: No active network interface found. Are you connected to a network?" -ForegroundColor Red
        exit 1
    }
    
    $gateway    = $defaultRoute.NextHop
    $ifaceIndex = $defaultRoute.InterfaceIndex
    
    # Retrieve the network adapter based on InterfaceIndex.
    $interface = Get-NetAdapter -InterfaceIndex $ifaceIndex -ErrorAction SilentlyContinue
    if (-not $interface) {
        Write-Host "Error: Could not retrieve network adapter information." -ForegroundColor Red
        exit 1
    }
    $ifaceName = $interface.Name
    
    Write-Host "Default Interface: $ifaceName" -ForegroundColor Green
    Write-Host "Gateway: $gateway" -ForegroundColor Green
    
    # Get the IPv4 address information.
    $ipInfo = Get-NetIPAddress -InterfaceIndex $ifaceIndex -AddressFamily IPv4 -ErrorAction SilentlyContinue |
        Where-Object { $_.IPAddress } |
        Select-Object -First 1
    if (-not $ipInfo) {
        Write-Host "Error: Could not retrieve IP address information." -ForegroundColor Red
        exit 1
    }
    $ip           = $ipInfo.IPAddress
    $prefixLength = $ipInfo.PrefixLength
    
    Write-Host "IP Address: $ip" -ForegroundColor Green
    
    # Convert the prefix length to a subnet mask.
    $netmask = Convert-PrefixToSubnetMask -PrefixLength $prefixLength
    Write-Host "Subnet Mask: $netmask" -ForegroundColor Green
    
    # Calculate the broadcast address.
    $ipInt = Convert-IPStringToInt -ip $ip
    
    $max = [uint32]::MaxValue
    # Compute the netmask integer as: max - (2^(32 - prefix) - 1)
    $netmaskInt = $max - ([uint32]([math]::Pow(2, (32 - $prefixLength)) - 1))
    # The inverse mask (host portion) is:
    $inv = $max - $netmaskInt
    
    # Calculate the broadcast integer: (IP AND netmask) OR inverse mask.
    $broadcastInt = ([uint32]($ipInt -band $netmaskInt)) -bor $inv
    
    $broadcast = Convert-IntToIPAddress -ipInt $broadcastInt
    Write-Host "Broadcast Address: $broadcast" -ForegroundColor Green
    
    # Get the MAC (hardware) address.
    $mac = $interface.MacAddress
    Write-Host "MAC Address: $mac" -ForegroundColor Green
    
    # Retrieve DNS servers for the interface.
    $dnsInfo = Get-DnsClientServerAddress -InterfaceIndex $ifaceIndex -AddressFamily IPv4 -ErrorAction SilentlyContinue
    $dnsServers = $dnsInfo.ServerAddresses -join ' '
    Write-Host "DNS Servers: $dnsServers" -ForegroundColor Green
    
    # Get the public IP address using an external service (api.ipify.org).
    try {
        $public_ip = Invoke-RestMethod -Uri "https://api.ipify.org"
        Write-Host "Public IP Address: $public_ip" -ForegroundColor Green
    } catch {
        Write-Host "Error retrieving public IP address." -ForegroundColor Red
    }
    
    # Perform a ping test to 8.8.8.8 and calculate the average latency.
    Write-Host "Performing ping test to 8.8.8.8..." -ForegroundColor Blue
    try {
        $pingResults = Test-Connection -ComputerName 8.8.8.8 -Count 3 -ErrorAction Stop
        if ($pingResults) {
            $avgLatency = ($pingResults | Measure-Object -Property ResponseTime -Average).Average
            Write-Host ("Average Latency (ping): {0:N2} ms" -f $avgLatency) -ForegroundColor Green
        } else {
            Write-Host "Ping test failed." -ForegroundColor Red
        }
    } catch {
        Write-Host "Ping test failed." -ForegroundColor Red
    }
    
    Write-Host "Detailed network information gathered successfully." -ForegroundColor Blue
  • macOS Public IP Checker Bash Script

    This Bash script uses curl to query ifconfig.me for your public IP address and then displays it in the Terminal on macOS.

    Click to view script…
    #!/bin/bash
    # check_public_ip.command - Display your public IP address on macOS
    # This script uses curl to query ifconfig.me, which returns your public IP address.
    # Usage: ./check_public_ip.command
    
    # Check if curl is installed
    if ! command -v curl &>/dev/null; then
      echo "Error: curl is not installed. Please install curl to use this script."
      exit 1
    fi
    
    echo "Fetching public IP address..."
    public_ip=$(curl -s ifconfig.me)
    
    if [ -z "$public_ip" ]; then
      echo "Error: Unable to retrieve public IP address."
      exit 1
    fi
    
    echo "Your public IP address is: $public_ip"
  • macOS Network Diagnostics & Information Tool Bash Script

    This Bash script collects detailed network information on a macOS system by querying system utilities (like routeifconfig, and ipconfig) and formatting the output with colored text for easy reading. It reports data such as the default gateway, active interface, IP address, subnet mask, broadcast address, MAC address, DNS servers, public IP, and average ping latency

    Click to view script…
    #!/bin/bash
    # netinfo_detailed.sh - Detailed network information for macOS
    
    # Define colors for output (ANSI escape codes)
    RED='\033[0;31m'
    GREEN='\033[0;32m'
    BLUE='\033[0;34m'
    NC='\033[0m' # No Color
    
    echo -e "${BLUE}Gathering default route information...${NC}"
    
    # Get the default gateway and active interface from the routing table.
    default_route=$(route -n get default 2>/dev/null)
    gateway=$(echo "$default_route" | awk '/gateway/ {print $2}')
    iface=$(echo "$default_route" | awk '/interface/ {print $2}')
    
    if [ -z "$iface" ]; then
      echo -e "${RED}Error: No active network interface found. Are you connected to a network?${NC}"
      exit 1
    fi
    
    echo -e "${GREEN}Default Interface: ${NC}$iface"
    echo -e "${GREEN}Gateway: ${NC}$gateway"
    
    # Get the IP address for the active interface.
    ip=$(ipconfig getifaddr "$iface")
    echo -e "${GREEN}IP Address: ${NC}$ip"
    
    # Retrieve the subnet mask in hexadecimal from ifconfig.
    # Expected format is like: "inet 192.168.1.2 netmask 0xffffff00 broadcast 192.168.1.255"
    mask_hex=$(ifconfig "$iface" | awk '/inet / {print $4}')
    # Remove any leading "0x" using sed so that we have exactly 8 hex digits.
    mask_hex=$(echo "$mask_hex" | sed 's/^0x//')
    if [ ${#mask_hex} -ne 8 ]; then
      echo -e "${RED}Unexpected netmask format: $mask_hex${NC}"
      netmask="Unknown"
    else
      mask1=$((16#${mask_hex:0:2}))
      mask2=$((16#${mask_hex:2:2}))
      mask3=$((16#${mask_hex:4:2}))
      mask4=$((16#${mask_hex:6:2}))
      netmask="${mask1}.${mask2}.${mask3}.${mask4}"
    fi
    echo -e "${GREEN}Subnet Mask: ${NC}$netmask"
    
    # Get the broadcast address from ifconfig output.
    broadcast=$(ifconfig "$iface" | awk '/broadcast/ {print $4}')
    echo -e "${GREEN}Broadcast Address: ${NC}$broadcast"
    
    # Get the MAC (hardware) address of the interface.
    mac=$(ifconfig "$iface" | awk '/ether/ {print $2}')
    echo -e "${GREEN}MAC Address: ${NC}$mac"
    
    # Retrieve DNS servers from /etc/resolv.conf.
    dns_servers=$(grep 'nameserver' /etc/resolv.conf | awk '{print $2}' | tr '\n' ' ')
    echo -e "${GREEN}DNS Servers: ${NC}$dns_servers"
    
    # Get the public IP address using an external service.
    public_ip=$(curl -s ifconfig.me)
    echo -e "${GREEN}Public IP Address: ${NC}$public_ip"
    
    # Perform a ping test to google.com and extract the average latency.
    echo -e "${BLUE}Performing ping test to google.com...${NC}"
    ping_result=$(ping -c 3 google.com 2>/dev/null)
    avg_rtt=$(echo "$ping_result" | tail -1 | awk -F'/' '{print $5}')
    if [ -n "$avg_rtt" ]; then
      echo -e "${GREEN}Average Latency (ping): ${NC}${avg_rtt} ms"
    else
      echo -e "${RED}Ping test failed.${NC}"
    fi
    
    echo -e "${BLUE}Detailed network information gathered successfully.${NC}"