import pcap, dpkt, socket import sys, time #Monitor your Browsing/Downloading data via Python # pc will capture network traffic pc = pcap.pcap() # the ports we want to listen # ports = (80, 8080, 443, 888) # for HTTP and HTTPS def process(): # this function listens to given ports mem = sport = dport = 0 try: # as long as there are new packets for ts, pkt in pc: # timestamp , packet eth = dpkt.ethernet.Ethernet(pkt) #print eth # print the who packet ''' example results look like Ethernet( src='\x00\x03G\xb2M\xe4', dst='\x00\x03G\x06h\x18', data=IP( src='\n\x00\x01\x1c', dst='\n\x00\x01\x10', sum=39799, len=60, p=1, ttl=128, id=35102, data=ICMP( sum=24667, type=8, data=Echo( id=512, seq=60160, data='blahblah')))) ''' ip = eth.data # now data is in ip if (ip.__class__ == dpkt.ip.IP): #source IP address and Destination address ip1, ip2 = map(socket.inet_ntoa, [ip.src, ip.dst]) # is the protocol TCP? if ip.p == socket.IPPROTO_TCP: # only listen to TCP traffic I7 = ip.data #source IP port and Destination port sport, dport = [I7.sport, I7.dport] # if the traffic in the port range we want to listen to # if (sport in ports or dport in ports): if (1==1): if len(I7.data) > 0: time_string = time.strftime('%x %X %Z', time.localtime(ts)); print '%s, packet from %s:%d to %s:%d, length: %d' %(time_string, ip1, sport, ip2, dport, len(I7.data)) mem = mem + len(I7.data) except KeyboardInterrupt: print '%s' % sys.exc_type print 'shutting down' print ('%d packets received, %d packets dropped' ' %d packets dropped by interface') % pc.stats() return int(mem) def main(): print "Start monitoring" mem = process() print float(mem/(1024*1024)), 'mb traffic monitored' return if __name__ == '__main__': main()
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question