Network Monitoring with Raspberry Pi: A Complete In-Depth Guide with Practical Code Examples

SBC Tutorials

As networks get more complicated, it’s more important than ever to keep an eye on how well they work, how safe they are, and how reliable they are. Users can find problems, improve performance, and spot possible threats when they can see what’s going on with the network, whether it’s at home, in a small business, or in a development lab. You can build a network monitoring system that runs all the time and gives you useful information on a Raspberry Pi, which is cheap and flexible.

To monitor a network, you need to gather information about devices, traffic, connectivity, and performance. You can then look at this data to see how the network is working and where it could use some work. Users can make their own monitoring solutions that fit their needs by using the Raspberry Pi, Python, and system tools together.

This guide goes into great detail about using Raspberry Pi to monitor networks. It talks about how to set up the system, collect data, and analyse it, and it gives real-world examples of how to use the code.

Understanding Network Monitoring Concepts

Network monitoring includes a lot of different tasks, such as keeping an eye on device availability, measuring latency, analysing traffic, and finding problems. Each of these things gives you an idea of how well the network is working and how healthy it is.

The main idea behind network monitoring is to keep an eye on how data moves between devices. This means figuring out which devices are on, how much bandwidth is being used, and if the connections are stable.

One practical example is keeping an eye on a home network to make sure all the devices are working properly. The monitoring system can find out if a device is unreachable and let the user know.

Another example is keeping an eye on how much bandwidth is being used to find devices that use too much data. This helps the network work better and keeps it from getting too busy.

Setting Up the Raspberry Pi for Monitoring

The Raspberry Pi needs to be ready before you can use monitoring tools. This includes setting up a compatible operating system, keeping software up to date, and making sure the network connection is stable.

For accurate monitoring, a wired Ethernet connection is best because it gives you consistent performance and less variability.

Giving the Raspberry Pi a static IP address makes it easy to access and add to the network.

Putting the Raspberry Pi in the middle of the network is a good example because it lets it keep an eye on traffic.

Basic Network Monitoring with Ping

One of the simplest forms of network monitoring is checking whether devices are reachable using ping. This involves sending packets to a device and measuring the response time.

The following Python script demonstrates how to monitor device availability:

import subprocess
import time

def ping_host(host):
    result = subprocess.run(["ping", "-c", "1", host], stdout=subprocess.DEVNULL)
    return result.returncode == 0

hosts = ["192.168.1.1", "192.168.1.100"]

while True:
    for host in hosts:
        status = "UP" if ping_host(host) else "DOWN"
        print(f"{host} is {status}")
    time.sleep(5)

This script continuously checks whether specified devices are reachable, providing a basic monitoring mechanism.

Monitoring Network Latency

Latency is an important metric that indicates how quickly data travels between devices. High latency can affect performance and user experience.

The following example measures latency:

import subprocess

def get_latency(host):
    result = subprocess.run(["ping", "-c", "1", host], capture_output=True, text=True)
    output = result.stdout
    if "time=" in output:
        return output.split("time=")[1].split(" ")[0]
    return None

latency = get_latency("8.8.8.8")
print(f"Latency: {latency} ms")

This script extracts the response time from a ping command, allowing users to monitor network performance.

Example: Continuous Latency Monitoring

A more advanced example involves logging latency over time:

import time

while True:
    latency = get_latency("8.8.8.8")
    print(f"Current latency: {latency} ms")
    time.sleep(2)

This provides real-time feedback on network conditions.

Monitoring Bandwidth Usage

Bandwidth monitoring helps identify how much data is being transmitted across the network. This can reveal patterns and highlight potential issues.

The following script reads network statistics:

def get_network_usage():
    with open("/proc/net/dev") as f:
        data = f.readlines()
    
    for line in data:
        if "eth0" in line:
            values = line.split()
            received = int(values[1])
            transmitted = int(values[9])
            return received, transmitted

rx, tx = get_network_usage()
print(f"Received: {rx} bytes, Transmitted: {tx} bytes")

This example provides a snapshot of network activity.

Example: Bandwidth Monitoring Over Time

import time

while True:
    rx, tx = get_network_usage()
    print(f"RX: {rx}, TX: {tx}")
    time.sleep(5)

This allows users to observe changes in network usage.

Detecting New Devices on the Network

Identifying devices connected to the network is an important aspect of monitoring. This helps detect unauthorized access.

import subprocess

def scan_network():
    result = subprocess.run(["arp", "-a"], capture_output=True, text=True)
    return result.stdout

print(scan_network())

This script lists devices currently visible on the network.

Example: Logging Device Activity

from datetime import datetime

def log_devices(devices):
    with open("devices.log", "a") as f:
        f.write(f"{datetime.now()}\n{devices}\n")

devices = scan_network()
log_devices(devices)

This creates a record of network activity for later analysis.

Monitoring Open Ports

Open ports can indicate active services on the network. Monitoring them helps identify potential vulnerabilities.

import socket

def check_port(host, port):
    s = socket.socket()
    s.settimeout(1)
    result = s.connect_ex((host, port))
    s.close()
    return result == 0

print(check_port("192.168.1.1", 80))

This script checks whether a specific port is open.

Example: Multi-Port Scan

ports = [22, 80, 443]

for port in ports:
    if check_port("192.168.1.1", port):
        print(f"Port {port} is open")

This helps identify active services.

Example: Alert System for Downtime

Monitoring systems can trigger alerts when devices go offline.

def alert(host):
    print(f"Alert: {host} is down")

while True:
    for host in hosts:
        if not ping_host(host):
            alert(host)
    time.sleep(5)

This example provides immediate feedback when issues occur.

Advanced Monitoring with Logging

Logging is essential for long-term analysis.

def log_event(message):
    with open("network.log", "a") as f:
        f.write(message + "\n")

log_event("Network monitoring started")

This creates a persistent record of events.

Example: Combining Multiple Metrics

while True:
    rx, tx = get_network_usage()
    latency = get_latency("8.8.8.8")
    
    print(f"RX: {rx}, TX: {tx}, Latency: {latency}")
    time.sleep(5)

This provides a comprehensive view of network performance.

Real-World Applications

There are many useful ways to use Raspberry Pi for network monitoring. At home, it helps make sure that devices are working properly and that bandwidth is being used well. It helps small businesses understand how their networks work and how safe they are.

For instance, a user might keep an eye on their network to find devices that shouldn’t be there. Another could keep an eye on bandwidth use to find out when a lot of data is being used.

In development environments, monitoring tools help you test and improve network settings.

Security and Best Practices

To stop people from abusing them, monitoring systems should be set up safely. Only authorised users should be able to see logs and use monitoring tools.

Regular updates keep the system safe and dependable. Looking at logs can help find problems and make things run better.

Conclusion

Raspberry Pi network monitoring is a strong and flexible way to see and control what’s going on on your network. Users can make their own monitoring systems that fit their needs by combining Python scripts with system tools.

The Raspberry Pi is a flexible platform for network monitoring, from simple connectivity tests to more in-depth analysis. When set up and maintained correctly, it becomes an essential tool for keeping the network safe and running smoothly.

 

Related posts

Automating Tasks with Cron Jobs: A Complete In-Depth Guide with Practical Code Examples

Creating a Raspberry Pi VPN Server: A Complete In-Depth Guide with Practical Code Examples

Raspberry Pi as a NAS (Network Storage): A Complete In-Depth Guide with Practical Code Examples