Monitor network traffic using eBPF via the bcc library. Write a C kernel probe counting TCP packets on a specific port and a Python userspace script reading the map and printing throughput every second.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
This is a great question about using eBPF (extended Berkeley Packet Filter) with the BCC (BPF Compiler Collection) library to monitor network traffic. I need to create:
A C kernel probe (eBPF program) that:
Counts TCP packets on a specific port
Stores this data in a kernel map
A Python userspace script that:
Loads and attaches the eBPF program
Reads the kernel map
Calculates and prints throughput every second
Let me think about the approach:
For the eBPF program, I need to:
Hook into a network tracepoint or kprobe
Check if it's a TCP packet
Check if it's on the target port
Increment a counter in a BPF map
Optionally track bytes for throughput calculation
For the Python script, I need to:
Use bcc library to compile and load the eBPF program
Attach it to the appropriate tracepoint/kprobe
Periodically read the map
Calculate throughput (packets and bytes per second)
Display the results
I'll use tracepoint/tcp/tcp_receive_reset or better yet, I can use kprobes on functions like tcp_v4_rcv or use the tracepoint/net/net_dev_queue or tracepoint/skb/skb_copy_datagram_iovec. Actually, the best approach is to use the tracepoint mechanism available in newer kernels, or use kprobes.
For a TCP port-specific monitor, I could use:
tracepoint/tcp/tcp_sendmsg and tracepoint/tcp/tcp_cleanup_rbuf (deprecated)
kprobe:tcp_v4_connect, kprobe:tcp_v4_rcv
tracepoint/sock/inet_sock_set_state - good for connection state changes
Using sock filters
The most practical approach is to use the kernel tracepoint tracepoint/tcp/tcp_sendmsg for outgoing traffic and create a kprobe for incoming TCP traffic, or filter by port using tracepoint/net/net_dev_queue. The cleanest solution for monitoring TCP packets on a specific port would be to hook into the TCP tracepoints directly, which gives me access to connection and packet information without needing complex socket filtering.
I'll use kprobes on tcp_v4_rcv for incoming IPv4 TCP packets since this is where all TCP packets arrive. The approach would involve parsing the packet to extract the destination port and incrementing a counter when it matches my target. However, kprobes on kernel functions can be fragile due to kernel version differences and function signature changes, so I need to be careful with how I access the packet data through the sk_buff structure.
A more robust approach would leverage tracepoints like tracepoint/tcp/tcp_receive_reset or tracepoint/sock/inet_sock_set_state which have stable interfaces across kernel versions. For production use, I should stream events using BPF_PERF_OUTPUT and parse packets at the network layer with tracepoint/net/net_dev_queue.
I'll create a solution using kprobes that properly accesses the socket structure to extract source/destination addresses and ports, storing connection data in a hash map.
Actually, using a tracepoint like tcp_sendmsg would be more practical since it's available in recent kernels and already exposes socket information directly, avoiding the complexity of manual structure parsing.
After weighing the options, I think the most reliable approach is leveraging tracepoint/sock/inet_sock_set_state for state changes or tracepoint/tcp/tcp_sendmsg for traffic events, as these are stable across modern kernel versions and provide socket context without requiring manual packet parsing.
Let me implement a practical solution using kprobes on tcp_v4_rcv to capture incoming packets and extract port information directly from the socket structure, while also hooking tcp_cleanup_rbuf to track data movement. This avoids the complexity of cgroup-based filtering and works reliably across different kernel configurations.
I'll structure the eBPF program to parse the socket buffer and extract both source and destination ports, then aggregate statistics by port in a map. ->packets, 1);
__sync_fetch_and_add(&stats->bytes, skb->len);
}
code
return 0;
}
I'm concerned about kernel compatibility with atomic operations on struct members. BCC has limitations with __sync_fetch_and_add on nested structures, so I should use a simpler approach with separate updates or tracepoints instead. Tracepoints like tcp_sendmsg or tcp_cleanup_rbuf would be more reliable across kernel versions. Let me build a practical solution using kprobes on tcp functions with straightforward increment logic and clear comments for maintainability.
The approach will hook into TCP packet processing to extract port information and accumulate statistics in a map, then expose this data through a Python userspace program that calculates throughput metrics.
For the kernel component, I need to carefully access the sk_buff structure and read port data. Using BPF_CORE provides the safest approach for kernel compatibility. The kprobe on tcp_v4_rcv intercepts incoming TCP packets, where I can extract the destination port and update per-port statistics. Since direct port extraction from sk_buff varies by kernel version, I'll aggregate traffic initially and filter by port in userspace, storing packet counts and byte totals in a hash map keyed by port number. I need to reconsider this approach. Using tracepoints would be more reliable, but they may not expose all the socket details I need. Let me pivot to a practical solution that actually works - hooking into the packet layer with BPF socket filters to capture port information directly from the network stack.
I'll set up a BPF program that attaches to socket operations and extracts the source and destination ports from the packet headers, storing the statistics in a hash map for retrieval. I'm overcomplicating the packet parsing with sk_buff. Let me reconsider the approach - using a kprobe on tcp_v4_rcv is more straightforward and widely supported. I can hook directly into the TCP receive path where the socket information is already available, rather than trying to manually parse packet headers from raw data. This gives me reliable access to port information without the complexity of boundary checking on packet buffers. I need to correct the byte order conversion - tcph.dest is already in network byte order, so I should use ntohs() to convert it to host order and get the actual port number. The ntohs() function converts from network order (big-endian) to host order, which gives us the numeric port value like 80 or 443.
Now I'm setting up the BPF program to read the packet data. I'll read the IP header first to verify it's TCP, then read the TCP header at the correct offset based on the IP header length. Once I have the TCP header, I can extract the destination port using ntohs() to properly convert from network byte order.
After getting the port, I need to update the hash maps for both packet and byte counts. I should verify the BCC API for how lookup_or_init actually works, and I need to define the ZERO constant that I'm referencing.
Looking at BCC's BPF_HASH implementation, lookup_or_init returns a pointer to the value, but I need to be careful about atomicity when incrementing. Let me use a cleaner approach with the standard BCC macros and properly read the packet data using bpf_probe_read_kernel. I'll include the necessary headers and define the hash maps, then read both the IP and TCP headers to extract the destination port and packet length for tracking.
For the Python side, I'll use BCC's attach_kprobe to hook into tcp_v4_rcv and periodically print the collected statistics from the kernel maps. _count = tcp_bytes.get(port, BPF.create_u64(0)).value
For each port, I'm calculating the packets per second and bytes per second by comparing current values against the previous snapshot, then displaying the rate along with the total packet count. After updating the stored values, I move the timestamp forward for the next iteration.
When the user interrupts the program, I need to handle the exit gracefully and provide a clean shutdown message.
Let me reconsider the eBPF implementation. The kernel probe needs to properly validate the packet structure before reading fields. I should verify it's actually a TCP packet by checking the protocol field, then calculate the correct offset to the TCP header based on the IP header length. Once I have the TCP header, I can extract the destination port and update the statistics map accordingly. If the port already exists in the map, I increment the counters; otherwise, I initialize a new entry. void *skb_data_ptr = (void *)(long)skb->data;
I'm reading the packet data from the skb buffer, first extracting the IP header to verify it's a TCP packet, then calculating the TCP header offset based on the IP header length and reading the TCP header to access the destination port. ```python
def format_bytes(self, bytes_val):
"""Format bytes to human-readable format"""
for unit in ['B', 'KB', 'MB', 'GB']:
if bytes_val < 1024.0:
return f"{bytes_val:.2f} {unit}"
bytes_val /= 1024.0
return f"{bytes_val:.2f} TB"
===========================================================================================================================================
TCP Network Traffic Monitor (eBPF-based)
===========================================================================================================================================
Monitoring all TCP ports...
Update interval: 1 second(s)
===========================================================================================================================================
Time Port In Pkts/s Out Pkts/s In Rate Out Rate Total In Total Out
===========================================================================================================================================
14:32:45 22 125.00 105.00 18.25 MB/s 15.50 MB/s 456.78 MB 389.45 MB
14:32:45 80 2340.00 1890.00 289.50 MB/s 234.20 MB/s 5.67 GB 4.23 GB
14:32:45 443 567.00 512.00 125.40 MB/s 98.30 MB/s 1.23 GB 945.60 MB
14:32:46 22 118.00 102.00 17.80 MB/s 14.90 MB/s 456.79 MB 389.46 MB
14:32:46 80 2315.00 1875.00 287.20 MB/s 232.10 MB/s 5.68 GB 4.24 GB
Key Features
✅ Dual Network Monitoring: Tracks both incoming and outgoing traffic
✅ Per-Port Statistics: Separate counters for each TCP port
✅ Throughput Calculation: Real-time bytes/sec and packets/sec rates
✅ Low Overhead: Kernel-space packet counting using eBPF
✅ Flexible Filtering: Monitor all ports or specific ports
✅ Human-Readable Output: Automatic unit conversion (B, KB, MB, GB)
✅ Real-time Updates: Configurable interval (default 1 second)
✅ Summary Report: Final statistics when exiting
This solution provides efficient network monitoring with minimal performance impact!
I need to see more of the next thinking to complete this thought. The output appears to be cut off at the print statement for the table header. Could you provide the complete next thinking section so I can properly finish rewriting this method? I cannot complete this thought. The partial thinking at the end ("One") doesn't have enough context or continuation in the next thinking to determine what consideration was being evaluated about the solution's robustness. I need to handle kernel version compatibility for the probe read function. In older kernels, `bpf_probe_read_kernel` doesn't exist, so I'll need to fall back to `bpf_probe_read`. For this example, I'll provide a working solution that accounts for this.
The kprobe attaches to `tcp_v4_rcv` and reads the packet data from the socket buffer. It extracts the IP header first to verify the protocol is TCP, then calculates the TCP header offset based on the IP header length and reads the TCP header to capture the destination port. The packet size and byte count are then recorded in the statistics hash map keyed by that port. I need to complete the partial thought from the next thinking and then summarize.
The kernel function reads the IP header to verify it's a TCP packet, then calculates the TCP header offset based on the IP header length. It proceeds to read the TCP header starting at that offset in the packet data. The function extracts the destination port in host byte order, then either updates an existing statistics entry for that port or creates a new one, using atomic operations to safely increment packet and byte counters.
The Python wrapper initializes a BPF object with the eBPF code and attaches it to the tcp_v4_rcv kernel function, printing confirmation on success or exiting if the program fails to load—typically due to insufficient permissions. } {'Throughput':<15} {'Total Packets':<15} {'Total Bytes':<15}")
print("=" * 110)
def print_stats(self):
"""Print and update statistics"""
current_time = time.time()
elapsed = current_time - self.prev_time
if elapsed <= 0:
return
# Get current timestamp for display
time_str = time.strftime('%H:%M:%S')
first_line = True
# Iterate through all monitored ports
for port_key, stats in self.port_stats_map.items():
port = port_key.value
# Skip if filtering by port and this isn't it
if self.target_port and port != self.target_port:
continue
packets = stats.packets
bytes_sent = stats.bytes
# Calculate deltas
if port in self.prev_stats:
prev_packets, prev_bytes = self.prev_stats[port]
pkt_diff = packets - prev_packets
bytes_diff = bytes_sent - prev_bytes
else:
pkt_diff = packets
bytes_diff = bytes_sent
# Calculate rates
pps = pkt_diff / elapsed
throughput_bps = bytes_diff / elapsed
throughput_str = f"{self.format_bytes(throughput_bps)}/s"
# Print row
time_col = time_str if first_line else ""
print(f"{time_col:<12} {port:<8} {pps:<12.1f} {throughput_b
ps:<15.1f} {throughput_str:<15} {packets:<15} {self.format_bytes(bytes_sent):<15}")
first_line = False
self.prev_stats[port] = (packets, bytes_sent)
self.prev_time = current_time
The main monitoring loop displays a formatted table with traffic statistics, updating every second. It prints headers and begins collecting data, catching keyboard interrupts to cleanly exit the monitoring session. I need to complete the argument parser setup and finalize the main function. The next section adds the port argument to the parser, processes command-line arguments, instantiates the TCPMonitor with the specified port, and runs the monitoring loop. After that, the script entry point is defined.
The implementation wraps up by accepting an optional port parameter via `-p` or `--port` flags, then launches the monitor with those settings. The main function ties together the argument parsing and monitor initialization to start the traffic analysis.</think>
# TCP Network Traffic Monitor using eBPF and BCC
I'll create a complete network traffic monitoring solution using eBPF with the BCC library. This includes a C kernel probe and a Python userspace script.
## Complete Solution
### 1. Python Script (tcp_monitor.py)
```python
#!/usr/bin/env python3
"""
TCP Network Traffic Monitor using eBPF
Counts packets and measures throughput per destination port
"""
import sys
import time
from bcc import BPF
from collections import defaultdict
import argparse
from datetime import datetime
# eBPF kernel code in C
EBPF_CODE = """
#include <uapi/linux/ptrace.h>
#include <net/sock.h>
#include <bcc/proto.h>
// Statistics structure for each port
struct port_statistics {
u64 packets_in;
u64 packets_out;
u64 bytes_in;
u64 bytes_out;
};
// Maps for incoming and outgoing traffic
BPF_HASH(tcp_ingress, u16, struct port_statistics);
BPF_HASH(tcp_egress, u16, struct port_statistics);
// Kprobe: Monitor incoming TCP packets
int kprobe__tcp_v4_rcv(struct pt_regs *ctx, struct sk_buff *skb)
{
void *skb_data_ptr = (void *)(long)skb->data;
// Read IPv4 header
struct iphdr ip_hdr = {};
bpf_probe_read_kernel(&ip_hdr, sizeof(ip_hdr), skb_data_ptr);
// Check if it's TCP (protocol 6)
if (ip_hdr.protocol != IPPROTO_TCP)
return 0;
// Calculate TCP header offset (IHL * 4 bytes)
u32 ip_hdr_len = ip_hdr.ihl * 4;
// Read TCP header
struct tcphdr tcp_hdr = {};
bpf_probe_read_kernel(&tcp_hdr, sizeof(tcp_hdr),
skb_data_ptr + ip_hdr_len);
// Extract destination port (convert from network byte order)
u16 dport = ntohs(tcp_hdr.dest);
// Get or initialize statistics for this port
struct port_statistics *stat = tcp_ingress.lookup(&dport);
if (stat) {
// Update existing entry atomically
__sync_fetch_and_add(&stat->packets_in, 1);
__sync_fetch_and_add(&stat->bytes_in, skb->len);
} else {
// Create new entry
struct port_statistics new_stat = {
.packets_in = 1,
.packets_out = 0,
.bytes_in = skb->len,
.bytes_out = 0
};
tcp_ingress.update(&dport, &new_stat);
}
return 0;
}
// Kprobe: Monitor outgoing TCP packets
int kprobe__tcp_sendmsg(struct pt_regs *ctx, struct sock *sk,
struct msghdr *msg, size_t size)
{
// Get socket family
u16 family = sk->__sk_common.skc_family;
if (family != AF_INET)
return 0;
// Extract destination port from socket
u16 dport = ntohs(sk->__sk_common.skc_dport);
if (dport == 0)
return 0;
// Get or initialize statistics
struct port_statistics *stat = tcp_egress.lookup(&dport);
if (stat) {
__sync_fetch_and_add(&stat->packets_out, 1);
__sync_fetch_and_add(&stat->bytes_out, size);
} else {
struct port_statistics new_stat = {
.packets_in = 0,
.packets_out = 1,
.bytes_in = 0,
.bytes_out = size
};
tcp_egress.update(&dport, &new_stat);
}
return 0;
}
"""
class TCPMonitor:
"""Monitor TCP traffic per port using eBPF"""
def __init__(self, target_port=None, update_interval=1):
self.target_port = target_port
self.update_interval = update_interval
self.prev_stats = {}
self.prev_time = time.time()
# Load eBPF program
try:
self.bpf = BPF(text=EBPF_CODE)
# Attach probes
self.bpf.attach_kprobe(event="tcp_v4_rcv",
fn_name="kprobe__tcp_v4_rcv")
self.bpf.attach_kprobe(event="tcp_sendmsg",
fn_name="kprobe__tcp_sendmsg")
print("✓ eBPF program loaded successfully")
print("✓ Attached to tcp_v4_rcv and tcp_sendmsg")
except Exception as e:
print(f"✗ Error loading eBPF program: {e}")
print(" Ensure you're running as root (sudo)")
sys.exit(1)
self.ingress_map = self.bpf["tcp_ingress"]
self.egress_map = self.bpf["tcp_egress"]
@staticmethod
def format_bytes(bytes_val):
"""Convert bytes to human-readable format"""
for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
if bytes_val < 1024.0:
return f"{bytes_val:>8.2f} {unit:>2s}"
bytes_val /= 1024.0
return f"{bytes_val:>8.2f} PB"
@staticmethod
def format_rate(rate):
"""Format data rate"""
for unit in ['B', 'KB', 'MB', 'GB']:
if rate < 1024.0:
return f"{rate:>8.2f} {unit:>2s}/s"
rate /= 1024.0
return f"{rate:>8.2f} TB/s"
def print_header(self):
"""Print statistics header"""
print("\n" + "=" * 130)
print(f"{'Time':<10} {'Port':<8} {'In Pkts/s':<12} {'Out Pkts/s':<12} "
f"{'In Rate':<17} {'Out Rate':<17} {'Total In':<17} {'Total Out':<17}")
print("=" * 130)
def collect_stats(self):
"""Collect current statistics from kernel maps"""
stats = {}
# Collect ingress stats
for port_key, in_stat in self.ingress_map.items():
port = port_key.value
if port not in stats:
stats[port] = {
'packets_in': 0, 'packets_out': 0,
'bytes_in': 0, 'bytes_out': 0
}
stats[port]['packets_in'] = in_stat.packets_in
stats[port]['bytes_in'] = in_stat.bytes_in
# Collect egress stats
for port_key, out_stat in self.egress_map.items():
port = port_key.value
if port not in stats:
stats[port] = {
'packets_in': 0, 'packets_out': 0,
'bytes_in': 0, 'bytes_out': 0
}
stats[port]['packets_out'] = out_stat.packets_out
stats[port]['bytes_out'] = out_stat.bytes_out
return stats
def calculate_rates(self, current_stats):
"""Calculate throughput rates"""
current_time = time.time()
elapsed = current_time - self.prev_time
if elapsed <= 0:
return {}, 0
rates = {}
for port, curr in current_stats.items():
if self.target_port and port != self.target_port:
continue
if port in self.prev_stats:
prev = self.prev_stats[port]
pkt_in_rate = (curr['packets_in'] - prev['packets_in']) / elapsed
pkt_out_rate = (curr['packets_out'] - prev['packets_out']) / elapsed
byte_in_rate = (curr['bytes_in'] - prev['bytes_in']) / elapsed
byte_out_rate = (curr['bytes_out'] - prev['bytes_out']) / elapsed
else:
pkt_in_rate = curr['packets_in'] / elapsed
pkt_out_rate = curr['packets_out'] / elapsed
byte_in_rate = curr['bytes_in'] / elapsed
byte_out_rate = curr['bytes_out'] / elapsed
rates[port] = {
'pkt_in_rate': pkt_in_rate,
'pkt_out_rate': pkt_out_rate,
'byte_in_rate': byte_in_rate,
'byte_out_rate': byte_out_rate,
'total_in': curr['bytes_in'],
'total_out': curr['bytes_out']
}
self.prev_stats = current_stats.copy()
self.prev_time = current_time
return rates, elapsed
def print_stats(self):
"""Print current statistics"""
current_stats = self.collect_stats()
rates, elapsed = self.calculate_rates(current_stats)
if not rates:
return
time_str = datetime.now().strftime('%H:%M:%S')
first_line = True
for port in sorted(rates.keys()):
rate = rates[port]
# Print row
time_col = time_str if first_line else ""
print(f"{time_col:<10} {port:<8} "
f"{rate['pkt_in_rate']:<12.1f} {rate['pkt_out_rate']:<12.1f} "
f"{self.format_rate(rate['byte_in_rate']):<17} "
f"{self.format_rate(rate['byte_out_rate']):<17} "
f"{self.format_bytes(rate['total_in']):<17} "
f"{self.format_bytes(rate['total_out']):<17}")
first_line = False
def print_summary(self):
"""Print final summary"""
stats = self.collect_stats()
print("\n" + "=" * 130)
print("Final Summary by Port:")
print("-" * 130)
print(f"{'Port':<8} {'Total In Pkts':<18} {'Total Out Pkts':<18} "
f"{'Total In Bytes':<18} {'Total Out Bytes':<18}")
print("-" * 130)
for port in sorted(stats.keys()):
stat = stats[port]
print(f"{port:<8} {stat['packets_in']:<18} {stat['packets_out']:<18} "
f"{self.format_bytes(stat['bytes_in']):<18} "
f"{self.format_bytes(stat['bytes_out']):<18}")
print("=" * 130)
def run(self):
"""Main monitoring loop"""
print("\n" + "=" * 130)
print("TCP Network Traffic Monitor (eBPF-based)")
print("=" * 130)
if self.target_port:
print(f"Monitoring port: {self.target_port}")
else:
print("Monitoring all TCP ports...")
print(f"Update interval: {self.update_interval} second(s)")
print("Press Ctrl+C to exit\n")
self.print_header()
try:
while True:
time.sleep(self.update_interval)
self.print_stats()
except KeyboardInterrupt:
self.print_summary()
print("\nMonitoring stopped.")
def main():
parser = argparse.ArgumentParser(
description='Monitor TCP network traffic using eBPF',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog='''
Examples:
sudo %(prog)s # Monitor all TCP ports
sudo %(prog)s -p 80 # Monitor only port 80
sudo %(prog)s --port 443 -i 2 # Monitor port 443, update every 2 seconds
'''
)
parser.add_argument('-p', '--port', type=int, dest='port',
help='Specific port to monitor (optional)')
parser.add_argument('-i', '--interval', type=float, default=1,
dest='interval',
help='Update interval in seconds (default: 1)')
args = parser.parse_args()
# Check for root
if sys.geteuid() != 0:
print("✗ This script requires root privileges (run with sudo)")
sys.exit(1)
monitor = TCPMonitor(target_port=args.port, update_interval=args.interval)
monitor.run()
if __name__ == "__main__":
main()