Inside PortPeek: High-Performance Architecture
A granular, technical breakdown of how PortPeek inspects local ports, resolves process metadata under least-privilege security tokens, probes HTTP/HTTPS protocols in sub-2ms, and renders native Windows 11 dark mode flyouts with zero dependencies.
The Native Execution Pipeline
Unlike developer utilities built on Electron, Python, or Tauri that package an entire Chromium browser runtime or spawn CLI subprocesses, PortPeek executes as a razor-thin Win32 subsystem application directly compiled into native x86-64 machine instructions.
Win32 Direct Kernel Queries vs CLI Wrappers (100x Benchmark)
Most port listing extensions and developer tools execute shell commands like netstat -ano or PowerShell's Get-NetTCPConnection. Spawning a new child process on Windows incurs heavy operating system overhead:
- Process creation requires
CreateProcessW, kernel token duplicate, virtual address space allocation, and loading system DLLs. - PowerShell must initialize the .NET Common Language Runtime (CLR), load PowerShell modules, query the Windows Management Instrumentation (WMI) CIM repository, and serialize output objects into text.
- Text streams must then be piped across standard I/O handles and parsed via regular expressions.
| Inspection Method | Execution Time | RAM Overhead | CPU Spike | Child Processes |
|---|---|---|---|---|
PortPeek (Direct GetExtendedTcpTable) |
0.04 ms (40 ยตs) | 0 MB (Reused buffer) | 0.00% | 0 |
netstat -ano | findstr |
120 โ 180 ms | 12 MB (cmd + netstat) | 3.5% | 2 (cmd.exe, findstr.exe) |
PowerShell Get-NetTCPConnection |
350 โ 550 ms | 45 โ 70 MB (CLR engine) | 12.0% | 1 (pwsh.exe) |
| Electron / Node.js background worker | 200 โ 400 ms | 120 โ 250 MB (V8 runtime) | 2.0% idle / 15% active | 3+ helper processes |
Authentic C++17 Implementation in PortPeek:
PortPeek queries both IPv4 (AF_INET) and IPv6 (AF_INET6) kernel listening tables in parallel using dynamic heap buffers that expand on demand:
void CollectIpv4Listeners(std::vector<RawBinding>& out) {
DWORD dwSize = 0;
DWORD ret = GetExtendedTcpTable(nullptr, &dwSize, FALSE, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0);
std::vector<BYTE> buffer;
while (ret == ERROR_INSUFFICIENT_BUFFER) {
buffer.resize(dwSize);
ret = GetExtendedTcpTable(buffer.data(), &dwSize, FALSE, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0);
}
if (ret == NO_ERROR && !buffer.empty()) {
auto* table = reinterpret_cast<PMIB_TCPTABLE_OWNER_PID>(buffer.data());
for (DWORD i = 0; i < table->dwNumEntries; ++i) {
const auto& row = table->table[i];
if (row.dwState == MIB_TCP_STATE_LISTEN) {
uint16_t port = ntohs(static_cast<u_short>(row.dwLocalPort & 0xFFFF));
if (port > 0) {
out.push_back({ port, row.dwOwningPid });
}
}
}
}
}
Least Privilege Architecture: Command-Line Inspection without UAC Elevation
To display human-friendly names like my-nextjs-app [Next.js] instead of a raw opaque node.exe, PortPeek must read the command-line arguments of the process listening on that port.
Traditional tools open target processes with broad access rights such as PROCESS_ALL_ACCESS or PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, then parse the remote Process Environment Block (PEB). This approach has a major security flaw: on Windows, attempting to read the PEB of another process triggers ERROR_ACCESS_DENIED (5) unless the utility is elevated with Administrator privileges via UAC.
PROCESS_QUERY_LIMITED_INFORMATION (standard medium integrity access token). It then dynamically resolves the undocumented NT system call NtQueryInformationProcess with class 60 (ProcessCommandLineInformation), available on Windows 8.1, 10, and 11.
constexpr PROCESSINFOCLASS ProcessCommandLineInformation = static_cast<PROCESSINFOCLASS>(60);
std::wstring GetProcessCommandLine(DWORD pid) {
auto pfnNtQuery = GetNtQueryInformationProcess();
if (!pfnNtQuery) return L"";
// Request only limited query permissions (Standard User Token)
HANDLE hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);
if (!hProcess) return L"";
struct HandleGuard {
HANDLE h;
~HandleGuard() { if (h) CloseHandle(h); }
} guard{ hProcess };
ULONG returnLength = 0;
// Step 1: Query required buffer size
NTSTATUS status = pfnNtQuery(hProcess, ProcessCommandLineInformation, nullptr, 0, &returnLength);
std::vector<BYTE> buffer(returnLength + sizeof(UNICODE_STRING));
// Step 2: Fetch Unicode string containing raw command line
status = pfnNtQuery(hProcess, ProcessCommandLineInformation, buffer.data(), static_cast<ULONG>(buffer.size()), &returnLength);
if (status >= 0) {
auto* pUnicodeStr = reinterpret_cast<PUNICODE_STRING>(buffer.data());
if (pUnicodeStr->Buffer && pUnicodeStr->Length > 0) {
return std::wstring(pUnicodeStr->Buffer, pUnicodeStr->Length / sizeof(wchar_t));
}
}
return L"";
}
Sub-2ms Non-Blocking Winsock Protocol Probing
How does PortPeek know whether a newly opened port is running HTTP or HTTPS, what framework title is being served, and whether it returns a 200 OK or 404 Not Found without freezing the UI thread?
PortPeek implements an asynchronous, non-blocking Winsock loopback probe:
- Non-Blocking I/O: Configures socket descriptor to non-blocking mode using
ioctlsocket(s, FIONBIO, &nonBlocking). - Disabling Nagle's Algorithm: Sets socket option
TCP_NODELAYto disable TCP packet coalescing, eliminating the default 200ms ACK delay. - Strict Microsecond Budget: Sets select timeout using
timevalto abort in under 2ms if the port is non-responsive or a non-HTTP binary stream (e.g. database wire protocol). - TLS Handshake Byte Inspection: Reads the first response byte: values
0x15(TLS Alert) or0x16(TLS Handshake) immediately identify HTTPS without hanging on SSL certificate handshakes.
HttpProbeResult ProbeLoopbackPort(uint16_t port, uint32_t timeoutMs) {
SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (s == INVALID_SOCKET) return {};
// 1. Enable Non-blocking mode
u_long nonBlocking = 1;
ioctlsocket(s, FIONBIO, &nonBlocking);
// 2. Disable Nagle algorithm
BOOL noDelay = TRUE;
setsockopt(s, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<const char*>(&noDelay), sizeof(noDelay));
// 3. Connect to 127.0.0.1:<port>
sockaddr_in addr{};
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
connect(s, reinterpret_cast<SOCKADDR*>(&addr), sizeof(addr));
// 4. Send fast HTTP GET probe
const char request[] = "GET / HTTP/1.1\r\nHost: localhost\r\nUser-Agent: PortPeek\r\nConnection: close\r\n\r\n";
send(s, request, sizeof(request) - 1, 0);
// 5. Inspect response header / TLS byte (0x15 / 0x16)
char chunk[2048];
int bytes = recv(s, chunk, sizeof(chunk), 0);
if (bytes > 0 && (chunk[0] == 0x15 || chunk[0] == 0x16)) {
// Automatically detected HTTPS endpoint
return { true /* isHttp */, true /* isHttps */ };
}
// ... parse <title> and HTTP Status Code
}
Windows 11 Dark Mode Menu Undocumented Ordinals
In Windows 10 and 11, standard Win32 popup menus (created via CreatePopupMenu and summoned with TrackPopupMenuEx) default to a bright blinding white background, even when the user has enabled system-wide Dark Mode.
To achieve authentic Windows 11 dark mode menus matching File Explorer and the Taskbar, PortPeek dynamically binds to undocumented APIs exported by ordinal inside uxtheme.dll:
| DLL Ordinal | Internal Function Signature | Target Windows Version | Role in PortPeek |
|---|---|---|---|
uxtheme.dll @ 135 |
SetPreferredAppMode(PreferredAppMode::AllowDark) |
Windows 10 1903+ / Windows 11 | Instructs the Win32 window manager to render dark menus and controls. |
uxtheme.dll @ 132 |
ShouldAppsUseDarkMode() |
Windows 10 1809+ / Windows 11 | Queries user personalization preference (Light vs Dark mode). |
uxtheme.dll @ 133 |
AllowDarkModeForWindow(HWND, BOOL) |
Windows 10 / Windows 11 | Enables immersive dark mode styling on the message-only window handle. |
uxtheme.dll @ 104 |
RefreshImmersiveColorPolicyState() |
Windows 10 / Windows 11 | Synchronizes live theme color state across the DWM compositor. |
uxtheme.dll @ 136 |
FlushMenuThemes() |
Windows 10 / Windows 11 | Flushes the internal GDI menu theme cache so new popups render instantly dark. |
void ThemeManager::Initialize() {
HMODULE hUxtheme = LoadLibraryExW(L"uxtheme.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
if (!hUxtheme) return;
m_RefreshImmersiveColorPolicyState = reinterpret_cast<fnRefreshImmersiveColorPolicyState>(
GetProcAddress(hUxtheme, MAKEINTRESOURCEA(104)));
m_ShouldAppsUseDarkMode = reinterpret_cast<fnShouldAppsUseDarkMode>(
GetProcAddress(hUxtheme, MAKEINTRESOURCEA(132)));
m_AllowDarkModeForWindow = reinterpret_cast<fnAllowDarkModeForWindow>(
GetProcAddress(hUxtheme, MAKEINTRESOURCEA(133)));
m_SetPreferredAppMode = reinterpret_cast<fnSetPreferredAppMode>(
GetProcAddress(hUxtheme, MAKEINTRESOURCEA(135)));
m_FlushMenuThemes = reinterpret_cast<fnFlushMenuThemes>(
GetProcAddress(hUxtheme, MAKEINTRESOURCEA(136)));
// Enable native dark mode on menus
if (m_SetPreferredAppMode) {
m_SetPreferredAppMode(PreferredAppMode::AllowDark);
}
if (m_FlushMenuThemes) {
m_FlushMenuThemes();
}
}
Per-Monitor V2 DPI Awareness & Taskbar Geometry
Developers frequently use mixed multi-monitor setups (for example, a 14-inch laptop display scaled at 150% alongside a 32-inch 4K external monitor at 100%).
PortPeek embeds a custom application manifest with PerMonitorV2 DPI awareness. When the menu is triggered, PortPeek queries the current monitor's DPI scaling factor via GetDpiForWindow and dynamically scales menu icon bitmaps, padding, and text metrics.
Furthermore, PortPeek uses SHAppBarMessage(ABM_GETTASKBARPOS) to locate the Windows taskbar (whether docked at the bottom, top, left, or right, or set to auto-hide) and positions the flyout popup menu flush with the notification area using TrackPopupMenuEx(hMenu, TPM_RIGHTALIGN | TPM_BOTTOMALIGN, pt.x, pt.y, hWnd, nullptr).
Offline & Zero-Telemetry Privacy Guarantee
PortPeek was designed with an absolute, uncompromising commitment to developer privacy:
127.0.0.1 to probe your local development servers.
How to Verify PortPeek's Network Behavior:
- Wireshark Capture: Filter traffic with
ip.addr == 127.0.0.1and confirm that zero outbound packets are transmitted to public IP addresses. - Sysinternals Process Monitor (ProcMon): Filter by process name
PortPeek.exeand observe that network operations are strictly limited toTCP Connect -> 127.0.0.1. - Open-Source Audit: Review the complete, unminified C++17 source code on GitHub.
Mobile LAN IP Resolution & ISO/IEC 18004 QR Engine
Testing responsive web applications on physical smartphones connected to your local Wi-Fi network requires two distinct technical challenges: discovering your non-loopback local network IPv4 address, and generating a 100% compliant QR code directly in GDI memory without third-party dependencies.
1. LAN IPv4 Resolution via GetAdaptersAddresses
Instead of invoking slow CLI utilities like ipconfig.exe, PortPeek queries the Windows IP Helper API (GetAdaptersAddresses with GAA_FLAG_INCLUDE_PREFIX). It iterates active physical network adapters, prioritizes IF_TYPE_IEEE80211 (Wi-Fi) and IF_TYPE_ETHERNET_CSMACD (Ethernet) with operational status IfOperStatusUp, and filters out loopback (127.x.x.x) and link-local auto-configuration (169.254.x.x) ranges.
2. ISO/IEC 18004 Standard QR Code Generation
PortPeek compiles a pure C implementation of the official Nayuki Model 2 QR engine (qrcodegen.c). It dynamically generates standard QR symbols with:
- Reed-Solomon Galois Field Arithmetic: Computes error-correction generator polynomials ($GF(2^8)$ modulo $x^8 + x^4 + x^3 + x^2 + 1$) for Error Correction Level M (~15% recovery capacity).
- Penalty Function Evaluation: Evaluates all 8 standard mask formulas to select the pattern with the lowest penalty score across runs, 3x3 blocks, finder-like patterns, and balance ratio.
- Double-Buffered 4-Module Quiet Zone: Renders crisp 7px modules onto an isolated white backing card with an exact 28px quiet zone, ensuring instant recognition by iOS Camera, Google Lens, and Android bar scanners.
Cloudflare Quick Tunnels, Custom Aliases & Latency Probing
PortPeek integrates first-class support for sharing localhost previews with remote clients and assigning custom human-readable aliases to microservices:
1. Non-Blocking Cloudflare Quick Tunnel Spawning
When triggering a public preview, PortPeek spawns cloudflared.exe tunnel --url http://localhost:<port> using Win32 CreateProcessW with CREATE_NO_WINDOW and redirected standard error pipes. An asynchronous reader thread scans output chunks for the ephemeral https://*.trycloudflare.com URL and copies it directly to the Windows clipboard within milliseconds.
2. Workspace .portpeek Alias Discovery Hierarchy
PortPeek looks for project metadata in a clean 4-tier discovery order:
- Workspace JSON:
.portpeekorportpeek.jsonin the detected project directory. - User Global Configuration:
%USERPROFILE%\.portpeek\config.json. - Registry Overrides:
HKCU\Software\PortPeek\Aliases. - Built-in Framework Heuristics: Automatic identification of Next.js, Vite, FastAPI, Django, Ollama, Redis, PostgreSQL, and more.