import binascii
import json



class Packet_Analyzer():
	def __init__(self):
		data=None
		
	def identify_protocol(self,hex_pkt):
		protocols=""
		if(b'6300' in hex_pkt and hex_pkt[84:88]==b'6300'):
			protocols=protocols+"enip:"
		if(b'0300' in hex_pkt and hex_pkt[108:112]==b'0300'):
			protocols=protocols+"s7comm:"
		if (b'810a' in hex_pkt and hex_pkt[84:88] == b'810a'):
			protocols = protocols + "bacnet:"
		if ((b'8000' in hex_pkt or b'c000' in hex_pkt) and (hex_pkt[84:88] == b'8000' or hex_pkt[84:88] == b'c000')):
			print("omron found")
			protocols = protocols + "omron:"
		if (b'0000' in hex_pkt and hex_pkt[108:112] == b'0000'):
			protocols = protocols + "modbus:"
		if(hex_pkt[46:48] == b"06"):
			protocols=protocols+"tcp"
		if (hex_pkt[46:48] == b"11"):
			protocols = protocols + "udp"
		return protocols

	def get_ip(self,hex_pkt):
		if(hex_pkt[24:28]==b"0800"):
			ip_inhex= hex_pkt[28+24:28+24+8]
			ip = str(int.from_bytes(binascii.unhexlify(ip_inhex[0:2]), byteorder="little"))+"."+str(int.from_bytes(binascii.unhexlify(ip_inhex[2:4]), byteorder="little"))+"."+str(int.from_bytes(binascii.unhexlify(ip_inhex[4:6]), byteorder="little"))+"."+str(int.from_bytes(binascii.unhexlify(ip_inhex[6:8]), byteorder="little"))
			return ip

	def get_mac(self,hex_pkt):
		souce_mac = hex_pkt[12:24].decode()
		modified_src_mac = ":".join(souce_mac[i:i + 2] for i in range(0, len(souce_mac), 2))
		return modified_src_mac

	def get_tcp_port(self,inhex):
		if(inhex[46:48]==b"06"):
			port = int(inhex[68:72], 16)
			return port

	def get_udp_port(self,inhex):
		if (inhex[46:48] == b"11"):
			port = int(inhex[68:72], 16)
			return port

	def find_mac(self,mac, trim_count=-1):
		try:
			if len(mac[:trim_count]) == 0:
				return "No Mac"
			else:
				res = self.data[mac[:trim_count]]
				return res
		except:
			r = self.find_mac(mac, trim_count - 1)
			return r

	def get_vendor(self,mac):
		f = open("utilities/mac_vendors.json")
		self.data = json.loads(f.read())
		vendor = self.find_mac(mac.upper())
		return vendor