Skip to content

How to Show Active TCP Connections for a Specific Process in Batch Script

Learn how to use Batch scripts with netstat and tasklist to filter and display active TCP connections for a specific process like chrome.exe or zoom.exe, helping troubleshoot bandwidth usage and network behavior.

Modern applications (like browsers or game launchers) often open dozens of background network connections simultaneously. When troubleshooting high bandwidth usage or suspicious network behavior, listing every connection on the machine is overwhelming. You need to "filter" the list down to a single application. A Batch script can combine netstat (to find the connections) and tasklist (to find the Process ID), allowing you to see exactly which IP addresses and ports a specific program (like chrome.exe or zoom.exe) is talking to.

This guide will explain how to isolate network activity for a specific process.

Method 1: The "Process-to-Port" Mapping Script

This script automatically finds all Process IDs (PIDs) for your application and then filters the netstat list for those PIDs.

@echo off
setlocal enabledelayedexpansion

set "ProcName=chrome.exe"

echo [SCAN] Finding connections for: %ProcName%...
echo.

:: First verify the process is running
tasklist /fi "imagename eq %ProcName%" /nh 2>nul | findstr /i "%ProcName%" >nul 2>&1
if !errorlevel! neq 0 (
    echo [ERROR] Process "%ProcName%" is not currently running.
    pause
    endlocal
    exit /b 1
)

:: Collect all unique PIDs for this process
set "PIDList="
set "PIDCount=0"

for /f "tokens=2" %%p in ('tasklist /fi "imagename eq %ProcName%" /nh 2^>nul ^| findstr /i "%ProcName%"') do (
    set /a PIDCount+=1
    set "PIDList=!PIDList! %%p"
)

echo [INFO] Found !PIDCount! instance(s^) of %ProcName%
echo.

:: Capture netstat output once (much faster than running it per PID)
set "TempFile=%TEMP%\netstat_proc.tmp"
netstat -ano > "%TempFile%" 2>&1

:: Display connections for each PID
set "TotalConnections=0"

echo   PROTO   LOCAL ADDRESS          FOREIGN ADDRESS        STATE            PID
echo   ============================================================================

for %%p in (!PIDList!) do (
    for /f "delims=" %%L in ('findstr /E " %%p" "%TempFile%" 2^>nul') do (
        echo   %%L
        set /a TotalConnections+=1
    )
)

echo   ============================================================================
echo.
echo [SUMMARY] %ProcName% has !TotalConnections! active connection(s^) across !PIDCount! process(es^).

:: Clean up
del "%TempFile%" >nul 2>&1

pause
endlocal

Output:

[SCAN] Finding connections for: chrome.exe...

[INFO] Found 3 instance(s) of chrome.exe

  PROTO   LOCAL ADDRESS          FOREIGN ADDRESS        STATE            PID
  ============================================================================
  TCP     [IP_ADDRESS]           [IP_ADDRESS]           ESTABLISHED      1234
  TCP     [IP_ADDRESS]           [IP_ADDRESS]           ESTABLISHED      1234
  TCP     [IP_ADDRESS]           [IP_ADDRESS]           ESTABLISHED      1234
  TCP     [IP_ADDRESS]           [IP_ADDRESS]           ESTABLISHED      1234
  ============================================================================

[SUMMARY] chrome.exe has 4 active connection(s) across 3 process(es).
Press any key to continue . . .

Method 2: Finding Connections for a Specific Service

If the application is a Windows Service (like a database or web server), you can use the service name to find its PID.

@echo off
setlocal enabledelayedexpansion

set "ServiceName=MSSQLSERVER"

echo [SERVICE AUDIT] Checking connections for service: %ServiceName%...
echo.

:: Find the PID for this service
set "ServicePID="
for /f "tokens=2" %%p in ('tasklist /svc /fi "services eq %ServiceName%" /nh 2^>nul ^| findstr /i "%ServiceName%"') do (
    set "ServicePID=%%p"
)

if not defined ServicePID (
    echo [ERROR] Service "%ServiceName%" is not running or does not exist.
    echo.
    echo [TIP] To list running services:
    echo       net start
    pause
    endlocal
    exit /b 1
)

echo [FOUND] Service "%ServiceName%" is running under PID: !ServicePID!
echo.

:: Get connection count
set "ConnCount=0"

echo   PROTO   LOCAL ADDRESS          FOREIGN ADDRESS        STATE
echo   ================================================================

for /f "delims=" %%L in ('netstat -ano ^| findstr /E " !ServicePID!"') do (
    echo   %%L
    set /a ConnCount+=1
)

echo   ================================================================
echo.

if !ConnCount! equ 0 (
    echo [INFO] No active network connections for this service.
) else (
    echo [INFO] !ConnCount! active connection(s^) found.
)

pause
endlocal

Method 3: Real-Time Connection Monitor

This script refreshes periodically to show when the application opens or closes connections, without using cls which destroys scroll history.

@echo off
setlocal enabledelayedexpansion

set "App=msedge.exe"
set "Interval=5"
set "TempFile=%TEMP%\connmon.tmp"

echo [MONITOR] Real-time connection tracker for %App%
echo          Refresh: every %Interval% seconds
echo          Press CTRL+C to stop.
echo.

:Loop
:: Check if the process is still running
tasklist /fi "imagename eq %App%" /nh 2>nul | findstr /i "%App%" >nul 2>&1
if !errorlevel! neq 0 (
    echo [!time!] %App% is not running. Waiting...
    timeout /t %Interval% >nul
    goto :Loop
)

:: Capture netstat once
netstat -ano > "%TempFile%" 2>&1

:: Collect PIDs and count connections
set "ConnCount=0"
set "EstabCount=0"
set "ListenCount=0"

for /f "tokens=2" %%p in ('tasklist /fi "imagename eq %App%" /nh 2^>nul ^| findstr /i "%App%"') do (
    for /f "tokens=4,5" %%s in ('findstr /E " %%p" "%TempFile%" 2^>nul') do (
        set /a ConnCount+=1
        if /i "%%s"=="ESTABLISHED" set /a EstabCount+=1
        if /i "%%s"=="LISTENING" set /a ListenCount+=1
    )
)

echo [!time!] %App% - Total: !ConnCount!  Established: !EstabCount!  Listening: !ListenCount!

timeout /t %Interval% >nul
goto :Loop

Method 4: Full Audit with Foreign Address Resolution

For security analysis, resolve the foreign IP addresses to hostnames to identify where your application is connecting.

@echo off
setlocal enabledelayedexpansion

set "ProcName=chrome.exe"
set "LogFile=%USERPROFILE%\process_connections.csv"

echo [AUDIT] Deep connection analysis for %ProcName%...
echo.

:: Verify process is running
tasklist /fi "imagename eq %ProcName%" /nh 2>nul | findstr /i "%ProcName%" >nul 2>&1
if !errorlevel! neq 0 (
    echo [ERROR] %ProcName% is not running.
    pause
    endlocal
    exit /b 1
)

:: CSV header
echo Date,Time,Process,PID,Protocol,LocalAddress,ForeignAddress,State,ForeignHost > "%LogFile%"

:: Capture netstat
set "TempFile=%TEMP%\netstat_audit.tmp"
netstat -ano > "%TempFile%" 2>&1

set "Count=0"

echo   Scanning connections and resolving addresses...
echo.

for /f "tokens=2" %%p in ('tasklist /fi "imagename eq %ProcName%" /nh 2^>nul ^| findstr /i "%ProcName%"') do (
    for /f "tokens=1-5" %%a in ('findstr /E " %%p" "%TempFile%" 2^>nul') do (
        set "proto=%%a"
        set "local=%%b"
        set "foreign=%%c"
        set "state=%%d"
        set "pid=%%e"

        :: Extract just the IP from foreign address (remove :port)
        for /f "tokens=1 delims=:" %%i in ("!foreign!") do set "foreignIP=%%i"

        :: Try to resolve the foreign IP (skip local/special addresses)
        set "hostname=N/A"
        if "!foreignIP!" neq "0.0.0.0" if "!foreignIP!" neq "127.0.0.1" if "!foreignIP!" neq "*" (
            for /f "tokens=2" %%h in ('ping -a -n 1 -w 500 !foreignIP! 2^>nul ^| findstr /i "Pinging"') do (
                if /i "%%h" neq "!foreignIP!" set "hostname=%%h"
            )
        )

        echo   !proto! !local! -^> !foreign! [!state!] ^(!hostname!^)
        echo !date!,!time!,%ProcName%,!pid!,!proto!,!local!,!foreign!,!state!,!hostname! >> "%LogFile%"
        set /a Count+=1
    )
)

echo.
echo [DONE] !Count! connection(s^) analyzed.
echo        Results saved to: %LogFile%

del "%TempFile%" >nul 2>&1

pause
endlocal

How to Avoid Common Errors

Wrong Way: Using netstat -b for Scripting

The netstat -b flag (which shows the .exe name directly) is very slow because it performs deep process inspection, and it requires administrator privileges. Its multi-line output format is also extremely difficult to parse programmatically.

Correct Way: Use tasklist to get the PID(s) first, then filter netstat -ano for those PIDs. It is significantly faster and doesn't always require elevation.

Wrong Way: Running netstat Inside the FOR Loop

If your target process has 20 PIDs (common for Chrome), running netstat -ano inside the loop means executing it 20 times, each taking several seconds.

Correct Way: Capture netstat -ano output to a temp file once, then filter it with findstr for each PID:

netstat -ano > "%TEMP%\netstat.tmp"
for %%p in (%PIDs%) do (
    findstr /E " %%p" "%TEMP%\netstat.tmp"
)

Wrong Way: Using findstr "%%p" Without End-of-Line Anchoring

Searching for PID 80 with plain findstr "80" will also match port :80, port :8080, PID 1800, PID 800, etc.

Correct Way: Use findstr /E " %%p" to match only at the end of the line (where the PID column is):

findstr /E " %%p" netstat_output.tmp

Wrong Way: Using cls in a Monitoring Loop

Clearing the screen every cycle destroys all previous output. You can never scroll back to see what happened 2 minutes ago.

Correct Way: Append a summary line each interval (Method 3) or write full details to a log file alongside the screen display.

Problem: Multiple PIDs for One App

Many modern applications (Chrome, Edge, Firefox, Teams) spawn dozens of child processes. Each has its own PID.

Solution: Use a FOR loop to collect all PIDs and check connections for each one. Methods 1 and 3 handle this automatically.

Best Practices and Rules

1. Identify "Foreign Address"

Pay close attention to the Foreign Address column. If you see your application talking to an IP in a country you don't recognize, it could be a sign of a compromised application or data exfiltration.

2. Understand Connection States

State Meaning
ESTABLISHED Actively sending/receiving data
LISTENING Waiting for incoming connections (server mode)
CLOSE_WAIT Remote side closed; app hasn't cleaned up yet
TIME_WAIT Connection closed; waiting for final cleanup
SYN_SENT Trying to connect (handshake in progress)

3. Log Connection Leaks

If you are troubleshooting a "leaking" connection that stays open too long, log the active connections to a file periodically. Method 3's rolling monitor helps identify when connections accumulate without being closed, a common symptom of application bugs.

4. Log File Location

Avoid using %CD% for log files, it depends on where the script is launched from. Use %USERPROFILE% or %TEMP% for reliable write access.

5. Always Use setlocal / endlocal

Without setlocal, every variable your script creates persists in the parent shell session, causing potential conflicts when running multiple scripts in sequence.

Conclusions

Displaying active TCP connections for a specific process provides "surgery-level" precision to your network troubleshooting. By filtering out the noise of the rest of the system and focusing on a single application, you can quickly identify performance bottlenecks, configuration errors, or security risks. This professional visibility is essential for managing networked applications and maintaining a clean, secure Windows environment.

Navigation