import socket, sys from struct import * #create an INET, STREAMing socket try: s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket . IPPROTO_T) except socket.error , msg: print 'Socket could not be created. Error Code : ' + str(msg[0]) + ' Message ' + msg[1] sys.exit() # receive a packet while True: packet = s.recvfrom(65500) #packet string from tuple packet = packet[0] #take first 20 characters for the ip header ip_header = packet[0:20] #now unpack them :) iph = unpack('!BBHHHBBH4s4s' , ip_header) version_ihl = iph[0] version = version_ihl >> 4 ihl = version_ihl & 0xF iph_length = ihl * 4 ttl = iph[5] protocol = iph[6] s_addr = socket.inet_ntoa(iph[8]); d_addr = socket.inet_ntoa(iph[9]); print 'Version : ' + str(version) + '\tIP Header Length : ' + str(ihl) + ' \tTTL : ' + str(ttl) + '\tProtocol : ' + str(protocol) + '\tSource Address : ' + str(s_addr) + '\tDestination Address : ' + str(d_addr) t_header = packet[iph_length:iph_length+20] #now unpack them :) th = unpack('!HHLLBBHHH' , t_header) source_port = th[0] dest_port = th[1] sequence = th[2] acknowledgement = th[3] doff_reserved = th[4] th_length = doff_reserved >> 4 print '\nSource port:' +str (source_port)+'\tDestination port:'+str (dest_port)+'\tSequence number:'+str(sequence) +'\tAcknowledgement:'+str(acknowledgement)+'\tT Header Length'+str(th_length)
h_size=iph_length +th_length*4 data_size=len(packet)-h_size #get data from the packet data=packet[h_size:] print 'Data : ' +data