CCNA 200-301

CCNP Enterprise

CCNP Security

CCIE Enterprise Lab

CCIE Security Lab

CCNP Service Provider

CCNP Data Center

CCNP Collaboration

CCIE DC Lab

Locating the exact TCP port number behind a network service or active connection is a routine necessity when troubleshooting port binding conflicts, writing firewall rules, auditing server exposure, or integrating unfamiliar hardware onto a LAN. Depending on whether you have local shell access, are probing a remote IP across the network, or need to catch a fleeting connection on the wire, the right discovery method changes. The sections below walk through how TCP port numbering works, where to look up authoritative protocol assignments, and how to identify active TCP ports across local operating systems, remote targets, packet captures, GUI scanners, and automated enterprise scripts.

Table of Contents

Understanding TCP Port Numbers and Common Default Ports

What is a TCP port number and how does it work?

A TCP port number is a 16-bit unsigned integer ranging from 0 to 65535 embedded in the Transmission Control Protocol header of every segment. While an IP address routes traffic to a specific host, the TCP port number identifies the exact application process or daemon socket on that host. Combined, an IP address and a TCP port form a socket pair (IP:Port), allowing a single machine to run web servers, database engines, and remote administration daemons simultaneously without mixing traffic streams.

How do well-known, registered, and ephemeral TCP port ranges differ?

Under IETF RFC 6335, the 65,536 possible TCP port numbers are divided into three distinct operational tiers:

  • Well-Known / System Ports (0–1023): Reserved for core internet protocols and privileged OS daemons. On Unix-like systems and modern Windows configurations, binding a listener in this range typically requires root or administrative privileges. Port 0 is reserved as a programming wildcard that instructs the operating system kernel to allocate any available port dynamically.
  • Registered / User Ports (1024–49151): Assigned to vendor applications, database servers, message brokers, and middleware frameworks that run under standard user accounts.
  • Dynamic / Private / Ephemeral Ports (49152–65535): Unassigned client-side source ports allocated temporarily by the OS network stack when initiating an outbound connection and recycled once the session closes. Note that many Linux distributions expand local ephemeral allocation to 32768–60999 via /proc/sys/net/ipv4/ip_local_port_range.

What is the difference between TCP and UDP port numbers?

TCP and User Datagram Protocol (UDP) maintain completely separate 16-bit port namespaces. A service listening on TCP port 53 does not conflict with another socket bound to UDP port 53 on the same IP address. Because TCP is connection-oriented and establishes sessions through a three-way handshake (SYN, SYN-ACK, ACK), active TCP ports always report explicit lifecycle states such as LISTEN, ESTABLISHED, CLOSE_WAIT, or TIME_WAIT. UDP ports are connectionless and stateless, meaning they hold no handshake state to query.

What are the most common default TCP port numbers?

Most standard network infrastructure services bind to predictable default TCP ports unless manually reconfigured:

  • 20 / 21: FTP (Data transfer / Control command channel)
  • 22: SSH, SCP, and SFTP
  • 25 / 587: SMTP (Mail relay / Authenticated client mail submission)
  • 53: DNS (Zone transfers and responses exceeding UDP payload limits)
  • 80 / 443: HTTP / HTTPS
  • 110 / 995: POP3 / POP3 over TLS
  • 143 / 993: IMAP / IMAP over TLS
  • 445: SMB (Windows file sharing and Active Directory)
  • 1433: Microsoft SQL Server
  • 3306: MySQL and MariaDB
  • 3389: Windows Remote Desktop Protocol (RDP)
  • 5432: PostgreSQL
  • 8080 / 8443: Alternate HTTP proxies and web management interfaces

When you encounter a port outside these familiar defaults and need to verify which protocol officially owns it, consult the canonical global port database detailed next.

Authoritative Port Lookup: The IANA Service Name and Port Number Registry

The Service Name and Transport Protocol Port Number Registry, maintained by the Internet Assigned Numbers Authority (IANA) pursuant to RFC 6335, is the official global database mapping transport-layer port numbers (0–65535) to registered protocol service names.

Official Registry Endpoints and Local Mirrors

  • Web Lookup Interface: https://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml
  • Downloadable Machine-Readable Datasets: Available in .csv, .xml, and plain-text formats under https://www.iana.org/assignments/service-names-port-numbers/ (for example, service-names-port-numbers.csv).
  • Local Operating System Reference Files: Operating systems ship a static subset of the IANA registry for local port-to-name resolution at /etc/services on Linux, BSD, and macOS, and at C:\Windows\System32\drivers\etc\services on Windows.

Registry Record Schema

Each authoritative entry in the IANA database exposes the following standardized fields:

  • Service Name: The unique identifier string used by applications and DNS SRV records (for example, https or postgresql).
  • Port Number: The assigned numeric value within the System (0–1023) or User (1024–49151) tiers.
  • Transport Protocol: The bound transport layer (tcp, udp, sctp, or dccp).
  • Description & Reference: Concise protocol summary alongside the governing RFC or specification document.
  • Assignee, Contact, & Dates: The organization or engineering body holding the registration, along with initial registration and modification dates.
  • Known Unauthorized Uses & Assignment Notes: Documented port collisions, deprecated aliases, or security advisories associated with the port.

Operational Scope Note: An IANA entry reflects formal protocol assignment rather than mandatory runtime enforcement. Any local or remote application can be configured to listen on an arbitrary TCP port, so confirming actual runtime bindings requires querying the host directly—starting with local Windows tools.

How to Find Active and Listening TCP Ports in Windows

On a Windows workstation or server, you can map open TCP ports directly to their owning executables using three built-in utilities without installing third-party software.

Method 1: Command Prompt (netstat and tasklist)

  1. Open Command Prompt as Administrator (Win + X > Terminal (Admin) or search cmd and select Run as administrator).
  2. List all active and listening IPv4 and IPv6 TCP endpoints numerically along with their Process IDs (PID):
    cmd
    netstat -ano | findstr "TCP"
  3. -a displays both active connections and listening server ports.
  4. -n prints IP addresses and port numbers numerically instead of resolving hostnames or /etc/services labels.
  5. -o appends the owning PID in the rightmost column.
    To isolate only bound server ports waiting for inbound traffic, filter by state:
    cmd
    netstat -ano | findstr "LISTENING"
  6. Match the PID from the output (for example, 4120) to its running application binary:
    cmd
    tasklist /fi "pid eq 4120"

    Alternatively, run netstat -abno in an elevated prompt to print the executable name directly beneath each socket entry.

Method 2: PowerShell (Get-NetTCPConnection)

  1. Launch an elevated PowerShell window.
  2. Query bound TCP listeners and join each OwningProcess ID to Get-Process in a single pipeline:
    powershell
    Get-NetTCPConnection -State Listen |
    Select-Object LocalAddress, LocalPort, State, OwningProcess,
    @{Name="ProcessName";Expression={(Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue).ProcessName}} |
    Sort-Object LocalPort |
    Format-Table -AutoSize
  3. To inspect a single TCP port (such as port 443) across all connection states (Listen, Established, TimeWait), filter with -LocalPort:
    powershell
    Get-NetTCPConnection -LocalPort 443

Method 3: Windows Resource Monitor (GUI)

  1. Press Win + R, type resmon.exe, and press Enter.
  2. Select the Network tab.
  3. Expand Listening Ports to view every bound TCP port alongside its Image (executable name), PID, bound Address, and Firewall Status (such as Allowed, not restricted). Expand TCP Connections directly above it to inspect live local-to-remote port pairs in real time.

If you are auditing a Linux server or container environment instead of a Windows host, equivalent socket-to-daemon mapping is handled from the terminal.

How to Audit Listening TCP Ports and Daemons in Linux

Modern Linux distributions provide direct kernel socket inspection through iproute2 (ss) and file-descriptor utilities (lsof). Always prefix these commands with sudo; without root privileges, Linux hides PID and daemon names for sockets owned by root or other system accounts.

Step 1: Audit Listening TCP Sockets with ss

ss queries kernel tcp_diag structures directly, making it faster and more detailed than older procfs parsers:

sudo ss -tlnp
  • -t: Restricts output to TCP sockets.
  • -l: Shows only sockets in the LISTEN state (replace -l with -a to include ESTAB and TIME-WAIT sessions).
  • -n: Forces numeric port output, bypassing /etc/services name translation referenced earlier.
  • -p: Prints the owning process name, pid, and socket file descriptor.

Inspect the Local Address:Port column carefully: 0.0.0.0:8080 or [::]:8080 means the port accepts external connections across interfaces, whereas 127.0.0.1:8080 restricts access strictly to local loopback processes.

Step 2: Find TCP Ports by Process ID or Port Number with lsof

Because Unix treats network sockets as open files, lsof excels at targeted lookups when you already know a daemon’s PID or suspect a specific port collision:

  • List all listening TCP sockets system-wide:
    bash
    sudo lsof -nP -iTCP -sTCP:LISTEN
  • Find every TCP port bound or connected by a specific PID (for example, PID 1842):
    bash
    sudo lsof -Pan -p 1842 -iTCP

    Always include -a (logical AND); omitting -a causes lsof to return all open files for PID 1842 plus every TCP socket across the entire system.
  • Identify which daemon holds a specific TCP port (for example, 3306):
    bash
    sudo lsof -nP -iTCP:3306

Step 3: Fallback Check with Legacy netstat

On legacy servers or minimal appliances where net-tools is installed instead of lsof, run the equivalent flag combination:

sudo netstat -tlnp

Local terminal commands require shell access to the host. When you need to discover open TCP ports on an external server, router, or network printer over the network, you must switch to active port probing.

How to Scan and Discover Open TCP Ports on a Remote IP Address

Active port discovery sends TCP handshake probes over the network to determine which ports on a remote IP are accepting connections. Only scan external hosts or subnets that you own or have explicit authorization to test.

Step 1: Test a Single Known Remote TCP Port

When verifying firewall reachability to a known service endpoint, use built-in single-port connection testers:

  • From Windows PowerShell:
    powershell
    Test-NetConnection -ComputerName 192.168.1.50 -Port 443

    Check the TcpTestSucceeded boolean (True confirms a completed TCP three-way handshake).
  • From Linux or macOS (nc / Netcat):
    bash
    nc -zv -w 3 192.168.1.50 443

    -z performs a zero-I/O handshake check without sending application data, -v prints verbose status, and -w 3 enforces a 3-second timeout.

Step 2: Scan Common Server Ports with Nmap

When you do not know which TCP ports a remote server exposes, use Nmap to sweep the top 1,000 most commonly used TCP ports:

sudo nmap -sS 192.168.1.50

Running -sS with elevated privileges executes a half-open SYN scan, whereas unprivileged users can run nmap -sT 192.168.1.50 for a full OS connect() scan. Nmap classifies probed ports into three primary states:
– open: Target port replied with SYN-ACK; an application is actively listening.
– closed: Target host is reachable and replied with RST; no process is bound to that port.
– filtered: A firewall or packet filter silently dropped the probe or returned an ICMP administrative prohibition, preventing confirmation.

Step 3: Discover Hardware and Non-Standard Ports (Printers, Routers, Appliances)

Network printers, managed switches, and routers frequently expose administration portals or print queues outside Nmap’s default 1,000-port list—or run web interfaces on custom high ports (8080, 8443, 9100 for JetDirect/RAW printing, 631 for IPP, or 515 for LPD). To scan all 65,535 TCP ports and fingerprint the exact daemon behind each open port, run:

sudo nmap -sS -sV -p- -T4 192.168.1.50

-p- instructs Nmap to sweep ports 1 through 65535, and -sV interrogates open ports to identify the underlying firmware, HTTP server, or print service banner.

Some network workflows still evade both local socket polling and inbound port scans—specifically ultra-brief outbound client connections or locked-down IoT devices that ignore inbound probes. In those cases, passive packet capture reveals the exact TCP port numbers directly from wire headers.

Capturing Short-Lived or Unknown TCP Ports with Wireshark and tcpdump

Inspecting live packet headers captures every TCP connection attempt at the wire level, even if a process opens a socket for only a few milliseconds before terminating.

Step 1: Start a Scoped Capture in Wireshark

  1. Open Wireshark with administrative or wireshark-group capture permissions.
  2. Double-click the active network interface carrying the traffic (or a switch SPAN/mirror port if monitoring an external hardware appliance).
  3. Reproduce the application login, sync action, or device boot sequence you want to analyze.

Step 2: Apply Wireshark Display Filters to Isolate TCP Ports

Type the following expressions into the top Display Filter bar and press Enter to strip away background noise:

  • Show all TCP packets involving a target device IP:
    text
    ip.addr == 192.168.1.120 && tcp
  • Show only initial outbound SYN connection requests:
    text
    tcp.flags.syn == 1 && tcp.flags.ack == 0

    This filter is the fastest way to find an unknown server port: because clients originate connections from random ephemeral ports (as covered in the port ranges FAQ above), the Destination Port of an initial SYN packet always reveals the exact listening service port the client is trying to reach.
  • Verify bidirectional traffic on a specific TCP port:
    text
    tcp.port == 8443

Step 3: Read Header Fields and Conversation Summaries

Click any captured packet and expand Transmission Control Protocol in the middle Packet Details pane to inspect Source Port and Destination Port. To compile a clean inventory of every TCP port used across the entire capture without clicking individual packets, navigate to Statistics > Conversations and open the TCP tab to sort all endpoints by Port A and Port B.

Step 4: Inspect TCP Ports on Headless Hosts with tcpdump

On remote Linux servers or firewall appliances without a desktop GUI, capture raw numeric TCP headers directly in the terminal:

sudo tcpdump -nn -i eth0 'tcp and host 192.168.1.120'

The -nn flag disables both DNS hostname lookups and service-name translation, printing exact SourceIP.SourcePort > DestIP.DestPort pairs in real time.

While CLI tools and packet analyzers handle deep diagnostics, dedicated GUI socket monitors and high-speed scanners streamline day-to-day visual inspection and subnet discovery.

Comparing Dedicated TCP Port Scanners and GUI Socket Viewers

Network port utilities fall into two distinct categories: local GUI socket viewers that monitor live process-to-port activity on your workstation, and remote network scanners that sweep external hosts and subnets.

ToolDiscovery ScopeSupported OSInterfaceStandout CapabilitiesPrimary Limitation
Nmap (with Zenmap)Remote networks & local hostWindows, Linux, macOSCLI + Zenmap GUIIndustry-standard SYN stealth scans, -sV service/banner detection, OS fingerprinting, and NSE automation scriptsSteeper CLI learning curve; raw packet scans require root/Administrator and Npcap on Windows
Sysinternals TCPViewLocal host sockets onlyWindowsGUI + tcpvcon CLIReal-time color-coded view of opening (green) and closing (red) sockets, instant PID/process mapping, and one-click connection terminationCannot probe remote IP addresses across a network
Angry IP ScannerRemote IP ranges & subnetsWindows, Linux, macOSGUIFast multi-threaded subnet sweeps with customizable TCP port lists and one-click CSV, TXT, or XML exportRequires a local Java runtime (JRE) and lacks deep protocol banner fingerprinting
NirSoft CurrPortsLocal host sockets onlyWindowsPortable GUIStandalone zero-install executable, custom port/process filter rules, and automated background logging of socket changesWindows-only and restricted strictly to local machine endpoints
RustScanRemote hosts & large port rangesWindows, Linux, macOS, DockerCLIAsynchronous engine capable of sweeping all 65,535 TCP ports in seconds and piping open ports directly into NmapCLI-only; aggressive default concurrency can trigger IDS alerts or firewall rate-limiting

Choose TCPView or CurrPorts when troubleshooting which local Windows background process is binding or cycling TCP ports in real time; choose Angry IP Scanner for quick visual LAN audits, and pair RustScan or Nmap when comprehensive remote 65,535-port coverage and service identification are required. When you need scheduled, dependency-free port verification across dozens of enterprise servers without installing third-party binaries, lightweight script templates provide repeatable CSV reporting.

Ready-to-Use PowerShell and Python TCP Port Audit Scripts

Replace the host lists, TCP port arrays, and timeout values in either template below to run an automated multi-host TCP port sweep and generate a timestamped tcp_port_audit.csv report.

PowerShell Multi-Host TCP Port Scanner (Invoke-TcpPortAudit.ps1)

Uses asynchronous .NET TcpClient sockets to avoid Test-NetConnection‘s multi-second timeout delays on closed ports:

# Customize target hosts, TCP ports, per-port timeout (ms), and output path
$TargetHosts = @("192.168.1.10", "192.168.1.20", "db01.corp.example.com")
$TargetPorts = @(22, 80, 443, 1433, 3389, 5432, 8080)
$TimeoutMs   = 500
$OutputCsv   = ".\tcp_port_audit.csv"

$AuditResults = foreach ($HostName in $TargetHosts) {
    foreach ($Port in $TargetPorts) {
        $Client = New-Object System.Net.Sockets.TcpClient
        try {
            $ConnectTask = $Client.ConnectAsync($HostName, $Port)
            $IsOpen = $ConnectTask.Wait($TimeoutMs) -and $Client.Connected
        } catch {
            $IsOpen = $false
        } finally {
            $Client.Dispose()
        }

        [PSCustomObject]@{
            Timestamp  = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")
            TargetHost = $HostName
            TcpPort    = $Port
            Status     = if ($IsOpen) { "Open" } else { "ClosedOrFiltered" }
        }
    }
}

$AuditResults | Export-Csv -Path $OutputCsv -NoTypeInformation
$AuditResults | Where-Object Status -eq "Open" | Format-Table -AutoSize

Cross-Platform Python 3 Concurrent TCP Port Scanner (tcp_port_audit.py)

Uses only the Python 3 standard library (socket, concurrent.futures, csv) with IPv4/IPv6 support:

#!/usr/bin/env python3
import csv
import socket
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import datetime, timezone

# Customize target hosts, TCP ports, timeout (seconds), concurrency, and CSV path
TARGET_HOSTS = ["192.168.1.10", "192.168.1.20", "db01.corp.example.com"]
TARGET_PORTS = [22, 80, 443, 1433, 3389, 5432, 8080]
TIMEOUT_SEC = 0.5
MAX_WORKERS = 50
OUTPUT_CSV = "tcp_port_audit.csv"


def check_tcp_port(host: str, port: int) -> dict:
    status = "ClosedOrFiltered"
    try:
        with socket.create_connection((host, port), timeout=TIMEOUT_SEC):
            status = "Open"
    except OSError:
        pass
    return {
        "timestamp": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
        "target_host": host,
        "tcp_port": port,
        "status": status,
    }


def main() -> None:
    targets = [(h, p) for h in TARGET_HOSTS for p in TARGET_PORTS]
    results = []
    with ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:
        futures = [executor.submit(check_tcp_port, h, p) for h, p in targets]
        for future in as_completed(futures):
            results.append(future.result())

    results.sort(key=lambda r: (r["target_host"], r["tcp_port"]))
    with open(OUTPUT_CSV, mode="w", newline="", encoding="utf-8") as csv_file:
        writer = csv.DictWriter(
            csv_file, fieldnames=["timestamp", "target_host", "tcp_port", "status"]
        )
        writer.writeheader()
        writer.writerows(results)


if __name__ == "__main__":
    main()

Conclusion

Finding a TCP port number comes down to matching your inspection method to your vantage point on the network. Reference the IANA registry when verifying standard protocol assignments, run Get-NetTCPConnection, netstat, ss, or lsof when mapping local sockets directly to host PIDs, and turn to nmap when discovering exposed services across remote servers or network hardware. When short-lived client sessions or undocumented appliances hide their activity from polling tools, packet captures in Wireshark or tcpdump expose the exact source and destination ports on the wire, while GUI monitors and scripted CSV sweeps keep ongoing port visibility repeatable across larger environments.

Please follow and like us:
Last modified: December 3, 2026

Author

Comments

Write a Reply or Comment

Your email address will not be published.