NetstatWrapper Tutorial — Integrate System Netstat into Your App
This tutorial shows how to integrate a simple NetstatWrapper into your application to run the system netstat command, parse its output, and expose structured connection data (TCP/UDP, local/remote addresses, ports, state, PID/program). Example code is in Go for clarity and cross-platform considerations; adapt to your language as needed.
What NetstatWrapper does
- Runs the system netstat (or equivalent) command.
- Normalizes output across platforms (Linux, macOS, Windows).
- Parses rows into a typed struct.
- Provides a small API: Run(), Parse(), Filter(), ExportJSON().
Design decisions
- Use the native netstat or platform-specific equivalents (ss on Linux can be faster; Windows uses netstat -ano).
- Prefer consuming stdout of the command instead of system APIs to keep wrapper lightweight and portable.
- Normalize fields: Protocol, LocalAddr, LocalPort, RemoteAddr, RemotePort, State, PID, Program.
- Expose filtering by protocol, state, port, PID.
- Return structured errors when parsing fails.
Data model
go
type ConnState string const ( StateListen ConnState = “LISTEN” StateEstablished ConnState = “ESTABLISHED” StateTimeWait ConnState = “TIME_WAIT” StateCloseWait ConnState = “CLOSE_WAIT” StateUnknown ConnState = “UNKNOWN” ) type NetConn struct { Protocol string // “tcp”, “udp” LocalIP string LocalPort int RemoteIP string RemotePort int State ConnState PID int Program string }
Platform command choices
- Linux: try
ss -tunapthen fallback tonetstat -tunap. - macOS: use
netstat -anv -p tcpandnetstat -anv -p udp. - Windows:
netstat -anoand map PID to program viatasklist /FI “PID eq.”
Implementation outline (Go)
- Execute platform-specific command with context and timeout.
- Read stdout and split into lines.
- Detect column header format and map column positions.
- Parse each line to NetConn, handling differences (address:port formats, IPv6, missing PID).
- Provide Filter functions and JSON export.
Key parsing examples
- Address format: “[::1]:80”, “127.0.0.1:22”, “0.0.0.0:53”.
- Some netstat variants show “Local Address” and “Foreign Address” as separated columns; others join port with address—use regex to split at the last colon for IPv4 and last ]: for IPv6.
- PID/program may appear as “1234/sshd” on Linux
-p; on Windows it’s only PID.
Example parsing helper (conceptual):
go
func splitHostPort(raw string) (host string, port int, err error) { // handle [ipv6]:port, ipv4:port, wildcard:* }
Example: Run & Parse (concise Go functions)
- RunCommand(ctx, cmdArgs) -> stdout string
- ParseNetstat(output, platform) -> []NetConn
- FilterConns(conns, opts) -> []NetConn
- ExportJSON(conns) -> []byte
(Full code omitted here for brevity — implement careful regex for address parsing and platform branches.)
Filtering and usage examples
- Filter by listening TCP sockets:
go
results := FilterConns(all, Filter{Protocol:“tcp”, State:“LISTEN”})
- Find processes listening on port 8080:
go
results := FilterConns(all, Filter{LocalPort:8080})
Exporting and monitoring
- Export JSON for dashboards:
json
[{“Protocol”:“tcp”,“LocalIP”:“0.0.0.0”,“LocalPort”:22,“RemoteIP”:“0.0.0.0”,“RemotePort”:0,“State”:“LISTEN”,“PID”:123,“Program”:“sshd”}]
- Run wrapper periodically (every 5s) and diff snapshots to detect new connections.
Security and permissions
- Some platforms require elevated permissions to see PID/program info. Handle missing PID gracefully.
- Validate/escape command args if taking inputs from users.
Testing
- Unit-test parsing with sample outputs from multiple OS versions.
- Integration test that runs on CI OS matrix or uses recorded sample outputs.
Next steps / Extensions
- Add an optional native backend using OS APIs (procfs on Linux, GetExtendedTcpTable on Windows) for more robust data.
- Support mapping PID→container/pod metadata for containerized environments.
- Add streaming API that yields connection events (open/close).
This tutorial gives a compact blueprint to build and integrate a NetstatWrapper into your app. Implement platform branches, robust parsing, and filtering to expose reliable connection data.
Leave a Reply