Python Forum

Full Version: Help Understanding Code
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello Everyone
So i had to create a program that reads pcap files, takes the IP packet and shows it in a certain format. I had to ask for help and the person that helped me, didn't really explain what each line is doing. So if anyone can help me ill appreciate it.

def main():
	try:
		sys.argv[1]
		dmp_file = sys.argv[1]
		fp_dmp_file = open(dmp_file,'rb')
		pcap = dpkt.pcap.Reader(fp_dmp_file)
		pack_num = 0
		total_size = 0
		for ts, buf  in pcap:
			pkt_len = len(buf)
			eth = dpkt.ethernet.Ethernet(buf)
			ip = eth.data
			src_ip = socket.inet_ntop(socket.AF_INET, ip.src)
			dst_ip = socket.inet_ntop(socket.AF_INET, ip.dst)
			src_port = ip.data.sport
			dst_port = ip.data.dport
			ttl = ip.ttl
			protocol = ip.get_proto(ip.p).__name__
			print_packet_info(ts,src_ip,src_port,dst_ip,dst_port,protocol,pkt_len,ttl)
			pack_num += 1
			total_size += pkt_len
		avg_size = total_size/pack_num
		print_summary(pack_num,total_size,avg_size)
	except Exception as e:
		#print(e)
		print("Error: please supply pcap filename!\n")

if __name__ == '__main__':
	main()
Why don't you start by adding comments about what you think is happening, and we can correct any misconceptions from there.