from typing import Iterable

from scapy.all import *
from scapy.layers.inet import IP


def ip_from_packets(packets: Iterable) -> str:
	"""
	Get the IP of the machine where the packets are recorded
	It is the IP which is present in all packets
	:param packets:list of packets
	:return: ip address
	"""
	IPs = {}
	for packet in packets:
		if IP in packet:
			ip_from_packet = [packet[IP].src, packet[IP].dst]
			for ip_address in ip_from_packet:
				if ip_address in IPs:
					IPs[ip_address] += 1
				else:
					IPs[ip_address] = 1
	return max(IPs, key=IPs.get)


def ip_from_pcap(file: str) -> str:
	"""
	Wrap the above function (ip_from_packets) to read from pcap
	:param file: file name/path
	:return: ip address
	"""
	packets = rdpcap(file)
	return ip_from_packets(packets)


if __name__ == "__main__":
	print(ip_from_pcap("capture.pcap"))
	print(ip_from_pcap("trickbot.pcapng"))
	print(ip_from_pcap("trickbot2.pcapng"))
