Monday, 25 November 2024

Check that when my python code is producing data, which network interface it is using

import psutil

from scapy.all import sniff, IP, TCP, raw

import logging

 

# Logging setup

logging.basicConfig(

    filename="network_interface_usage.log",  # Log file

    level=logging.INFO,

    format="%(asctime)s - %(message)s",

    datefmt="%Y-%m-%d %H:%M:%S"

)

 

def log_and_print(message):

    """Logs the message to a file and prints it to the console."""

    print(message)

    logging.info(message)

 

def get_network_interface():

    """Returns a list of network interfaces and their IP addresses."""

    interfaces = psutil.net_if_addrs()

    interface_info = {}

    for interface, addrs in interfaces.items():

        for addr in addrs:

            if addr.family == psutil.AF_INET:  # Filter for IPv4 addresses

                interface_info[interface] = addr.address

    return interface_info

 

def packet_callback(packet):

    """Callback function to process captured packets."""

    if IP in packet and TCP in packet:

        ip_src = packet[IP].src

        ip_dst = packet[IP].dst

        tcp_sport = packet[TCP].sport

        tcp_dport = packet[TCP].dport

 

        # Log packet details

        log_and_print(f"Packet from {ip_src}:{tcp_sport} -> {ip_dst}:{tcp_dport}")

        log_and_print(f"  Raw Packet Data: {raw(packet).hex()}")

        log_and_print("-" * 50)

 

def capture_packets(interface):

    """Start sniffing packets on a specific interface."""

    log_and_print(f"Starting packet capture on {interface}...")

    sniff(iface=interface, prn=packet_callback, store=False)

 

def main():

    # Get all network interfaces and IPs

    interfaces = get_network_interface()

    log_and_print("Detected Network Interfaces and IPs:")

    for interface, ip in interfaces.items():

        log_and_print(f"Interface: {interface} - IP: {ip}")

 

    # Capture packets on each interface (you can choose one based on your setup)

    for interface in interfaces.keys():

        capture_packets(interface)

 

if __name__ == "__main__":

    main()


No comments:

Post a Comment