Categories
General

Monitor Network Connections

I developed this monitoring script after repeatedly needing to troubleshoot connectivity issues with Ollama, a local AI model runner. While working with multiple models and clients simultaneously, I needed to quickly identify which connections were active, which ports were being used, and whether connections were properly establishing or terminating. Standard task managers didn’t provide this network-specific detail. This tool offers real-time visibility into exactly which addresses and ports Ollama (or any process) is communicating with, making it significantly easier to diagnose configuration problems, optimize connection handling, and ensure proper network resource utilization without resorting to complex packet sniffers or enterprise monitoring solutions.

The PowerShell script

This script serves IT professionals who require immediate visibility into application network activity. It’s essential when troubleshooting connectivity issues with services like Ollama or Docker, verifying proper API connections, or investigating unexpected network traffic. System administrators rely on it to monitor client connections, validate port usage, and test firewall configurations. Security analysts find it valuable for identifying connection leaks and auditing external communications. The flexibility to filter by process name or PID makes it adaptable for both broad system monitoring and targeted analysis without specialized tools—perfect for quick diagnostics in complex environments.

function Monitor-ProcessConnections {
    param (
        [Parameter(Mandatory=$true, ParameterSetName="ByName")]
        [string]$ProcessName,
        
        [Parameter(Mandatory=$true, ParameterSetName="ByPID")]
        [int]$ProcessID,
        
        [Parameter(Mandatory=$false)]
        [int]$RefreshSeconds = 2
    )
    
    Write-Host "Press Ctrl+C to exit monitoring" -ForegroundColor Yellow
    
    try {
        while($true) {
            $processes = if ($ProcessName) {
                Get-Process -Name $ProcessName -ErrorAction SilentlyContinue
            } else {
                Get-Process -Id $ProcessID -ErrorAction SilentlyContinue
            }
            
            if (-not $processes) {
                $targetInfo = if ($ProcessName) { "named '$ProcessName'" } else { "with PID $ProcessID" }
                Write-Host "No process $targetInfo is currently running." -ForegroundColor Red
                Start-Sleep -Seconds $RefreshSeconds
                Clear-Host
                continue
            }
            
            foreach ($process in $processes) {
                $id = $process.Id
                $name = $process.ProcessName
                
                Write-Host "`nConnections for $name (PID: $id) [Press Ctrl+C to exit]" -ForegroundColor Green
                
                $connections = Get-NetTCPConnection | Where-Object OwningProcess -eq $id | 
                               Select-Object LocalAddress, LocalPort, RemoteAddress, RemotePort, State
                
                if ($connections) {
                    $connections | Format-Table
                } else {
                    Write-Host "No active connections found." -ForegroundColor Gray
                }
            }
            
            Start-Sleep -Seconds $RefreshSeconds
            Clear-Host
        }
    } catch {
        Write-Host "Error: $_" -ForegroundColor Red
    } finally {
        Write-Host "Monitoring stopped." -ForegroundColor Yellow
    }
}

# Example usage:
# By name: Monitor-ProcessConnections -ProcessName "ollama"
# By PID:  Monitor-ProcessConnections -PID 1234
# Custom refresh: Monitor-ProcessConnections -ProcessName "ollama" -RefreshSeconds 5

# Prompt the user for input
$inputType = Read-Host "Enter '1' to search by process name or '2' to search by PID"

if ($inputType -eq "1") {
    $processName = Read-Host "Enter the process name to monitor"
    Monitor-ProcessConnections -ProcessName $processName
} elseif ($inputType -eq "2") {
    $processPID = Read-Host "Enter the process PID to monitor"
    Monitor-ProcessConnections -ProcessID ([int]$processPID)
} else {
    Write-Host "Invalid selection. Exiting." -ForegroundColor Red
}

Step-by-step guide on how to use the code

Step 1: Save the code

  1. Open a text editor like Notepad
  2. Copy and paste the entire script
  3. Save the file with a .ps1 extension, for example: Monitor-Connections.ps1

Step 2: Run the script in PowerShell

You have two options for running the script:

Option A: Run PowerShell as Administrator

  1. Click the Start button
  2. Type “PowerShell”
  3. Right-click on “Windows PowerShell” and select “Run as administrator”
  4. Navigate to the folder where you saved the script using the cd command:
cd C:\path\to\your\script\folder\Monitor-Connections.ps1

Option B: Right-click method

  1. Navigate to the folder where you saved the script in File Explorer
  2. Right-click the script file
  3. Select “Run with PowerShell” (this might require running as administrator afterward if you don’t have the necessary permissions)

Step 3: Using the script
Once you run the script:

  1. It will prompt you to enter 1 to search by process name or 2 to search by PID
  2. Then:
    • If you chose option 1: Enter the process name (e.g., “ollama”, “chrome”, etc.)
    • If you chose option 2: Enter the process ID number (e.g., 1234)
  3. The script will start monitoring and show all active connections
  4. To stop monitoring, press Ctrl+C

Note about permissions

The Get-NetTCPConnection cmdlet often requires administrator privileges, which is why running PowerShell as administrator is recommended. If you try to run the script without these privileges, you might see permission errors.