import re
from collections import defaultdict
import matplotlib.pyplot as plt

def parse_file(file_path):
    with open(file_path, 'r') as file:
        data = file.read()

    pattern = re.compile(r'Source address: /(\d+\.\d+\.\d+\.\d+).*?Destination address: /(\d+\.\d+\.\d+\.\d+).*?Source port: (\d+).*?Destination port: (\d+)', re.DOTALL)
    matches = pattern.findall(data)

    return matches

def count_occurrences(matches):
    counts = defaultdict(int)
    for src_ip, dst_ip, src_port, dst_port in matches:
        counts[(src_ip, dst_ip, dst_port)] += 1

    return counts

def plot_data(counts):
    src_ips = []
    dst_ips = []
    ports = []
    occurrences = []

    for (src_ip, dst_ip, port), count in counts.items():
        src_ips.append(src_ip)
        dst_ips.append(dst_ip)
        ports.append(port)
        occurrences.append(count)

    fig, ax = plt.subplots(figsize=(10, 8))

    bar_width = 0.35
    index = range(len(src_ips))

    bars = ax.bar(index, occurrences, bar_width, label='Occurrences')

    ax.set_xlabel('IP and Port Combinations')
    ax.set_ylabel('Occurrences')
    ax.set_title('Occurrences of Source IPs, Destination IPs, and Ports')
    ax.set_xticks(index)
    ax.set_xticklabels([f'{src_ips[i]} -> {dst_ips[i]}:{ports[i]}' for i in range(len(src_ips))], rotation=90)
    ax.legend()

    plt.tight_layout()
    plt.show()

# File path to your text file
file_path = 'sample.txt'

matches = parse_file(file_path)
counts = count_occurrences(matches)
plot_data(counts)
