🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Network Monitoring: Packets, Flows and Anomaly Detection

Network DefenseMonitoring and DetectionđŸŸĸ Free Lesson

A firewall log tells you which policy allowed a session. A packet capture tells you what that session actually did. Most detection blind spots come from operating at only one of those levels: a team that ships flow records but never inspects payloads misses command-and-control traffic tunneling through valid DNS lookups, while a team that lives inside Wireshark cannot answer six-month questions because the capture files were deleted last Tuesday. Real monitoring stacks deliberately combine cheap, always-on signals with expensive, on-demand depth so that an analyst can start wide and zoom in without re-architecting anything.

Packets, flows, or logs: choosing the right evidence

Every source answers a different class of question, and each carries a different storage and processing cost. The mistake most teams make is picking one and treating it as sufficient. Packet capture is the only source that preserves application payloads, which is why it is irreplaceable during an investigation, but full capture on a busy link can generate hundreds of gigabytes per day. Flow records summarize who spoke to whom, for how long, and how many bytes moved, at a tiny fraction of that volume, yet they cannot show you the request body. Logs and metrics fill the remaining gaps at almost no cost.

Evidence sourceGranularityStorage costQuestion it answers best
Packet captureEvery byte of every frameVery highWhat exactly did this session exchange?
Flow records (NetFlow/sFlow)Session metadataLowWhich host talked to which, and how much?
IDS alertsRule matches on trafficLowDoes this match a known attack signature?
DNS query logsEach resolution requestLowWhich domains did this workstation resolve?
Interface counters (SNMP)Per-port throughputVery lowWhere is the network saturating right now?

A practical rule is to keep the cheap sources permanently and the expensive source on a rolling window of a few days, with a documented trigger for when an analyst preserves a specific capture as evidence.

Capturing a clean baseline with tcpdump

Start every investigation by capturing narrowly. A capture filtered at the interface level costs far less disk than one you trim afterwards, and a smaller file loads instantly in any analyzer. The command below writes only inbound HTTP traffic from a single host to a pcap file, which is usually enough to reconstruct a suspicious request without recording credentials for the entire subnet.

# Capture HTTP traffic to and from one suspicious host
sudo tcpdump -i eth0 -nn -s 0 \
  -w /var/tmp/case-4187.pcap \
  'host 10.20.4.55 and (port 80 or port 443)'

# Summarize the capture: talkers, ports and packet counts
tcpdump -nn -r /var/tmp/case-4187.pcap | awk '{print $3, $5}' | sort | uniq -c | sort -rn | head

# Extract only DNS queries for offline review
tcpdump -nn -r /var/tmp/case-4187.pcap 'udp port 53' -q | grep -i 'A?'

Reading a capture with -r and piping it into awk turns thousands of lines into a ranked list of conversations, which is usually enough to spot a host that never appears in the baseline. Keep the original pcap untouched: once you edit or re-save it, hash values change and the file loses value as evidence.

Display filters that answer one specific question

Capture filters decide what reaches the disk; display filters decide what you see while investigating. Good analysts write filters that encode a hypothesis rather than ones that dump everything. The set below covers the four questions that recur in almost every triage session: who is POSTing data, which domain was resolved, which connections were refused, and which host is pushing unusually large frames off the network.

Architecture Diagram
# HTTP POST requests, the usual exfiltration channel
http.request.method == "POST"

# A specific domain observed in DNS queries
dns.qry.name == "update-check-cdn.example"

# Connection attempts that were never completed
tcp.flags.syn == 1 and tcp.flags.ack == 0

# Host sending frames larger than 10 KB (bulk transfer)
frame.len > 10000 and ip.src == 10.20.4.55

Notice that each filter is narrow enough to be falsifiable. If the domain filter returns nothing, you have a real answer rather than an overwhelming list. Build a small personal library of these expressions and keep them next to your runbook so that a night-shift analyst inherits your reasoning instead of rediscovering it.

Turning flow records into traffic trends

Flow export gives you history without the disk penalty of packet capture. On a Cisco device the configuration is a handful of lines, and the collector side does the heavy lifting. Enable ingress and egress accounting per interface, then point the exporter at your collector over a non-standard UDP port that only your monitoring server can reach.

interface GigabitEthernet0/1
 description uplink-to-core
 ip flow ingress
 ip flow egress
!
ip flow-export version 9
ip flow-export destination 10.10.9.20 9996
ip flow-export source Loopback0
ip flow-cache timeout active 60

Once flows land in a collector, baselines become straightforward to compute: group by source and destination, bucket into five-minute windows, and compare the current window against the same window yesterday. Flow data also exposes reconnaissance quickly, because a port scan shows up as hundreds of one-packet sessions from the same source to different destination ports — a pattern that never looks like normal client behavior.

Statistical anomaly detection that survives real traffic

Thresholds written by hand break as soon as traffic grows or a marketing campaign ships. A statistical baseline adapts instead. The simplest defensible model is a rolling z-score: keep the mean and standard deviation of a metric over a recent window, then flag any point that drifts more than a chosen number of standard deviations from that window. Traffic has daily and weekly seasonality, so compare against the same period in previous days rather than against the immediately preceding hour.

python
import statistics
from datetime import datetime, timedelta

def build_baseline(history, weekday_only=True):
    """history: list of (timestamp, bytes_per_second) samples."""
    return [v for _, v in history]

def is_anomalous(baseline, current, z_threshold=3.0):
    if len(baseline) < 30:
        return False
    mean = statistics.fmean(baseline)
    stdev = statistics.pstdev(baseline)
    if stdev == 0:
        return False
    z_score = (current - mean) / stdev
    return abs(z_score) > z_threshold, round(z_score, 2)

baseline = build_baseline(yesterday_same_window)
flag, z = is_anomalous(baseline, current_bps)
if flag:
    alert(f"Outbound bandwidth z={z} at {datetime.utcnow()}")

Two details decide whether this works in production. First, guard against a zero standard deviation, which happens on quiet links and would otherwise flag every sample. Second, raise the threshold during periods when the metric is legitimately noisy; a fixed value of two produces alerts all night on an always-on international service.

Alert thresholds that hold up under load

Detection engineering is mostly calibration. The table below reflects targets that mature teams converge on, together with the failure mode each number is meant to prevent.

SignalHealthy targetFailure it prevents
New external destination per hostFewer than 5 per hourMissed beaconing to fresh infrastructure
Failed outbound loginsFewer than 10 per hour per userCredential stuffing going unnoticed
Bandwidth deviationWithin 3 standard deviationsExfiltration hidden in routine transfers
DNS query diversityFewer than 200 unique domains per hostDomain generation algorithms at scale
IDS signature matchesReviewed within 15 minutesReal intrusions buried in noise

Tune with data rather than opinion: replay a week of benign traffic through your rules, measure the false-positive count, and only then decide whether the rule earns a page at 3 a.m. A rule that fires fifty times a night gets muted, and a muted rule detects nothing.

💡Prove the pipeline before you trust it

Inject one synthetic beacon into a test segment every week — a beaconing domain, a large upload, a scan. If the alert does not arrive within your stated mean time to detect, your monitoring stack has quietly failed.

Common Mistakes

Storing full packet capture indefinitely and running out of disk mid-incident

Fix: Keep a rolling window of a few days, archive on demand, and rely on flow and DNS records for long-horizon history.

Alerting on raw thresholds such as more than 100 connections, tuned once and never revisited

Fix: Use rolling statistical baselines per host and per time-of-day, then review false-positive rates monthly.

Monitoring only the perimeter and trusting the internal network

Fix: Instrument east-west paths with sensors or switched port analyzers, because most lateral movement never leaves the building.

Filtering captures so aggressively that the evidence needed for the report is missing

Fix: Capture narrowly for triage, but preserve an unfiltered copy of the full session the moment an incident is declared.

Best Practices

  • Keep three permanent cheap signals — flow records, DNS logs, and interface metrics — and treat packet capture as a targeted investigation tool.
  • Write display filters that encode a hypothesis so an empty result is itself a useful finding.
  • Baseline traffic per host and per time window before applying any anomaly threshold across the whole network.
  • Time-sync every sensor with NTP; correlated evidence is impossible when clocks drift by minutes.
  • Review alert quality on a fixed cadence and delete rules that never produced a true positive.

Key Takeaways

  • Layered monitoring combines cheap always-on evidence with expensive targeted depth; no single source answers every question.
  • Capture filters reduce disk and evidence weight, while display filters structure the hypothesis you are testing.
  • Flow records scale to months of history and expose scans as clusters of one-packet sessions.
  • Statistical baselines with z-scores beat hand-written thresholds, provided you guard against zero variance and daily seasonality.
  • An alerting rule earns its place only after it is replayed against known-benign traffic and produces an acceptable false-positive rate.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Cybersecurity Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement