ngrep – grep Applied to Network Traffic: A Comprehensive Guide

In the realm of network troubleshooting and analysis, the ability to quickly sift through network traffic to find specific patterns is invaluable. Tools like grep have long been staples for text searching in files, but what if you need to apply that same pattern-matching power to network packets? Enter ngrep—short for "network grep"—a command-line utility that bridges the gap between packet capture tools (like tcpdump) and text search tools (like grep).

ngrep intercepts network packets, parses their payloads, and allows users to filter them using regular expressions, making it ideal for tasks like debugging HTTP requests, hunting for specific strings in network traffic, or monitoring application-layer protocols. Whether you’re a system administrator, developer, or security analyst, ngrep is a lightweight yet powerful tool to add to your network analysis toolkit.

This blog will dive deep into ngrep, covering its core functionality, installation, syntax, common use cases, advanced techniques, best practices, and limitations. By the end, you’ll be equipped to leverage ngrep to efficiently analyze network traffic with precision.

Table of Contents#

  1. What is ngrep?
  2. Installation
  3. Basic Syntax
  4. Core Features
  5. Common Use Cases with Examples
  6. Advanced Usage
  7. Best Practices
  8. Limitations
  9. Frequently Asked Questions
  10. References

What is ngrep?#

ngrep is a network packet analyzer that combines the packet-capturing capabilities of tcpdump with the pattern-matching power of grep. It operates on network traffic, capturing packets from specified interfaces (or pcap files) and filtering them based on user-defined regular expressions.

Unlike tcpdump, which focuses on capturing and saving packets, ngrep is designed to search packet payloads for text patterns, making it ideal for quickly identifying specific data (e.g., API keys, error messages, or protocol-specific commands) in real-time or recorded traffic. It supports a wide range of protocols, including TCP, UDP, ICMP, and raw IP, and integrates with libpcap (the same library used by tcpdump and Wireshark) for packet capture.

Installation#

ngrep is available for most Unix-like operating systems (Linux, macOS, BSD). Below are installation instructions for common platforms.

The easiest way to run ngrep is via Docker, which avoids local installation entirely:

docker pull ghcr.io/jpr5/ngrep:latest
docker run --rm --net=host --cap-add=NET_RAW ghcr.io/jpr5/ngrep:latest -q 'GET|POST' tcp port 80

This approach is ideal for quick, one-off captures or when you want to avoid installing packages on the host system.

Linux (Debian/Ubuntu)#

sudo apt update && sudo apt install ngrep -y

Linux (RHEL/CentOS/Fedora)#

sudo yum install epel-release -y && sudo yum install ngrep -y   # RHEL/CentOS
# Or for Fedora:
sudo dnf install ngrep -y

macOS (via Homebrew)#

brew install ngrep

Windows#

Native Windows builds (ngrep.exe) are available from the ngrep GitHub releases page and run via the Npcap driver (WinPcap is deprecated). The latest version supports both x86_64 and ARM64 architectures. You can also run ngrep via WSL (Windows Subsystem for Linux).

Build from Source#

For the latest features or custom configurations, you can build from source. See the INSTALL file in the ngrep repository for detailed instructions.

Basic Syntax#

The general syntax for ngrep is:

ngrep [options] "pattern" [bpf_filter]
  • pattern: The regular expression or literal string to search for in packet payloads.
  • bpf_filter: Optional Berkeley Packet Filter (BPF) expression to filter packets by protocol, port, IP, etc. (e.g., tcp port 80, host 192.168.1.100).

Key Options#

OptionDescription
-iCase-insensitive search.
-vInvert match (show packets that do not contain the pattern).
-qQuiet mode—suppresses some packet metadata for cleaner output.
-xShow hexadecimal and ASCII dump of packet payloads.
-XInterpret the search pattern as a hexadecimal string.
-wMatch the pattern as a whole word (word boundaries).
-W <format>Set output format: byline (split payload into lines), single (single-line output), or none (suppress payload). Hex/ASCII dumping is provided by -x flag.
-d <interface>Specify the network interface to monitor (e.g., -d eth0). Use -d any to capture on all interfaces.
-LList available network interfaces and exit.
-tPrepend timestamps to output.
-TShow time delta between matches.
-DReplay packets from a pcap file using the recorded time delays between them.
-n <count>Stop after capturing <count> matching packets.
-O <file>Save matching packets to a pcap file (for later analysis).
-I <file>Read packets from a pcap file (instead of live capture).
-s <snaplen>Set packet snapshot length (bytes to capture per packet).
-rResolve Docker/Podman container IPs to container names in output (v1.49+).
-uDisplay UTF-8 data in packet payloads (v1.49+).

Core Features#

ngrep's power lies in its ability to combine packet capture with regex-based pattern matching. Here are its standout features:

  1. Regex Support: Uses POSIX extended regular expressions (ERE) for flexible pattern matching (e.g., user=.*pass=.* to find login credentials). As of v1.49, PCRE2 is also supported and is the default on macOS and Windows builds.
  2. Protocol Filtering: Focus on specific protocols (TCP, UDP, ICMP) using BPF filters.
  3. Payload Inspection: View raw packet payloads in ASCII, hex, or line-by-line format.
  4. File I/O: Read packets from pcap files (-I) or save matches to pcap (-O) for offline analysis.
  5. BPF Integration: Leverage BPF filters to narrow traffic by IP, port, or protocol before applying regex (e.g., tcp port 443).
  6. Container Name Resolution: When running on a host with Docker or Podman containers, use -r to resolve ephemeral container IPs to meaningful container names in the output (v1.49+).
  7. UTF-8 Support: Display UTF-8 encoded data in packet payloads with the -u flag (v1.49+).

Common Use Cases with Examples#

Let’s walk through practical scenarios where ngrep shines, with concrete examples.

1. Monitor HTTP Traffic for Specific Requests#

Goal: Capture HTTP GET/POST requests containing the string "api/v1".

ngrep -i "GET /api/v1" "tcp port 80" -d eth0
  • -i: Case-insensitive search.
  • "GET /api/v1": Pattern to match.
  • "tcp port 80": BPF filter to limit to HTTP (port 80) traffic.
  • -d eth0: Monitor interface eth0.

Output:

interface: eth0 (192.168.1.0/255.255.255.0)
filter: ((ip or ip6) and (tcp port 80))
match: GET /api/v1

T 192.168.1.100:54321 -> 203.0.113.5:80 [AP]
GET /api/v1/users HTTP/1.1..Host: example.com..User-Agent: curl/7.68.0..Accept: */*....

2. Search for Credentials in Plaintext Traffic#

Goal: Find packets containing "password=" in unencrypted (e.g., HTTP) traffic.

ngrep -x "password=.*" "tcp port 80 or tcp port 8080"
  • -x: Show hex and ASCII dump (useful for verifying context).
  • "password=.*": Regex to match "password=" followed by any characters.
  • BPF filter: Monitor ports 80 (HTTP) and 8080 (common web app port).

3. Debug DNS Queries#

Goal: Monitor DNS traffic to see which domains a client is querying.

Note: DNS wire format encodes domain labels with length prefixes instead of literal dots (e.g., \x07example\x03com instead of "example.com"), so literal string matches for full domains with dots will fail. Search for partial domain labels instead:

ngrep -t "example" "udp port 53" -W byline
  • -t: Add timestamps.
  • "example": Match DNS queries containing "example" (partial label match).
  • "udp port 53": BPF filter for DNS (UDP port 53).
  • -W byline: Split payload into lines for readability.

4. Read Packets from a Pcap File#

Goal: Analyze a saved pcap file (e.g., from tcpdump) for "error" messages.

ngrep -I capture.pcap "error" -i
  • -I capture.pcap: Read from capture.pcap.
  • "error" -i: Case-insensitive search for "error".

5. Save Matching Packets to a Pcap File#

Goal: Capture all HTTP traffic (port 80) containing "JWT" and save to jwt_traffic.pcap.

ngrep "JWT" "tcp port 80" -O jwt_traffic.pcap
  • -O jwt_traffic.pcap: Save matches to a pcap file for later analysis in Wireshark.

6. Debug Docker Container Traffic#

Goal: Monitor HTTP traffic between containers in a Docker Compose stack, with container names instead of ephemeral IPs.

ngrep -r -d br-a1b2c3 -W byline -q 'GET|POST' port 80
  • -r: Resolve Docker container IPs to their names (requires v1.49+).
  • -d br-a1b2c3: Monitor the Docker Compose bridge network interface.
  • -W byline: Split payload into lines for readability.
  • -q: Quiet mode for cleaner output.

Output:

container: using docker socket for real-time events
T frontend(172.20.0.3):39212 -> backend(172.20.0.5):80 [AP]
GET /api/users HTTP/1.1.
Host: backend:80.
...

Advanced Usage#

For more complex scenarios, combine ngrep with advanced options and BPF filters.

Combine BPF Filters and Regex#

Narrow traffic to a specific IP and port, then search for a pattern:

ngrep -i "POST /login" "host 192.168.1.200 and tcp port 80" -d wlan0
  • BPF filter: host 192.168.1.200 and tcp port 80 (traffic to/from 192.168.1.200 on HTTP).
  • Regex: -i "POST /login" (case-insensitive search for login requests).

Payload Formatting#

ngrep is a stateless tool that performs per-packet matching. Use the -W byline option to format the display of individual packets by honoring embedded linefeeds:

ngrep -W byline "sessionid=" "tcp port 8080"

Limit Packet Capture#

Stop after 10 matching packets with -n, or limit capture size with -s (snaplen):

ngrep "GET" "tcp port 80" -n 10 -s 1024  # Capture first 10 matches, 1024 bytes per packet

Best Practices#

To use ngrep effectively and responsibly:

  1. Run with Sufficient Privileges: Packet capture requires root/administrator access. Use sudo on Linux/macOS.

    sudo ngrep "pattern" ...
  2. Specify Interfaces Explicitly: Avoid capturing on all interfaces (default behavior) to reduce noise. Use -d <interface>.

  3. Limit Scope with BPF Filters: Narrow traffic early with BPF (e.g., host 10.0.0.5, tcp port 443) to reduce processing overhead.

  4. Avoid Overly Broad Regex: Complex regex (e.g., .*) can slow ngrep and return irrelevant results. Be specific (e.g., user=[a-zA-Z0-9]+).

  5. Secure Captured Data: If capturing sensitive data (e.g., credentials), restrict access to pcap files (chmod 600 file.pcap).

  6. Respect Legal and Ethical Boundaries: Only capture traffic you own or have explicit permission to monitor. Unauthorized packet capture may violate privacy laws.

Limitations#

While powerful, ngrep has limitations:

  • No Deep Protocol Decoding: Unlike Wireshark, ngrep does not parse complex protocols (e.g., HTTP headers, DNS fields) beyond basic payload inspection.
  • Encrypted Traffic: It cannot decrypt TLS/SSL traffic (e.g., HTTPS). Use tools like tcpdump with Wireshark (and decryption keys) for encrypted content.
  • Performance: On high-traffic networks, ngrep may drop packets if the system cannot keep up with capture/filtering.
  • No GUI: Limited to command-line output, which may be less intuitive for complex analysis compared to Wireshark.
  • No Reassembly: ngrep operates on a per-packet basis and does not reassemble TCP streams. Multi-packet payloads may not display as a single coherent message.

Frequently Asked Questions#

What is the difference between ngrep and tcpdump?#

tcpdump is a general-purpose packet capture tool focused on capturing and filtering packets based on network headers (IP, port, protocol). ngrep adds pattern-matching capabilities on top of packet capture, allowing you to search packet payloads using regular expressions. Use tcpdump for capturing and saving traffic; use ngrep when you need to quickly find specific strings or patterns in live or recorded traffic.

Can ngrep decrypt HTTPS or TLS traffic?#

No. ngrep cannot decrypt TLS/SSL-encrypted traffic. To inspect encrypted payloads, you need to use a TLS interception proxy (like mitmproxy) or analyze traffic with Wireshark using the appropriate decryption keys.

How do I search for a literal string instead of a regex?#

By default, ngrep interprets the match expression as a regular expression. To search for a literal string, you can escape special regex characters or use hexadecimal matching with -X. For simple cases, just avoid regex metacharacters in your pattern.

Why does ngrep require root/sudo?#

Packet capture requires raw access to network interfaces, which is a privileged operation on Unix-like systems. Always run ngrep with sudo or as root.

How do I list available network interfaces?#

Use ngrep -L to list all available network interfaces that ngrep can capture on.

What is the latest version of ngrep?#

As of 2026, the latest stable version is ngrep 1.49.0 (released February 2026). It includes features like Docker/Podman container name resolution (-r), UTF-8 display support (-u), and PCRE2 regex support. Download it from the ngrep GitHub releases page.

References#

By mastering ngrep, you gain a fast, flexible tool to hunt for patterns in network traffic—whether debugging an application, investigating a security incident, or monitoring network behavior. With features like Docker container name resolution and PCRE2 support in version 1.49, ngrep remains a relevant and practical choice for modern network troubleshooting. Combine it with tcpdump for capture and Wireshark for deep analysis, and you'll have a robust network troubleshooting stack.