I have a python scripts that captures the packets on the ethernet using dpkt, but how do i differentiate between which packets are tcp and which ones are for udp.
Eventually i would like to have a list of packets for each tcp connection that was established during the time interval.
my code is:
import dpkt
import pcapy
cap=pcap.open_live('eth0',100000,1,0)
(header,payload)=cap.next()
while header:
eth=dpkt.ethernet.Ethernet(str(payload))
ip=eth.data
tcp=ip.data
# i need to know whether it is a tcp or a udp packet here!!!
(header,payload)=cap.next()
IP header contains field protocol. dpkt should allow you to obtain this value and using it you can guess what is on top of IP. Here is a list of valid protocols numbers http://www.iana.org/assignments/protocol-numbers/protocol-numbers.xml. UDP is equal to 17 while TCP is 6.
Edit:
I have checked this issue and as I mentioned dpkg provide p
properties to access protocol field of IP. So you can check agains it. But it also automatically parse packet and set data
property to instance of class that represent upper protocol like UDP or TCP. So you can check type of data
property and you recognize this protocol.
from dpkt.ip import IP, IP_PROTO_UDP
from dpkt.udp import UDP
ip = IP('E\x00\x00"\x00\x00\x00\x00@\x11r\xc0\x01\x02\x03\x04\x01\x02\x03\x04\x00o\x00\xde\x00\x0e\xbf5foobar')
#if ip.p == IP_PROTO_UDP: # checking for protocol field in ip header
if type(ip.data) == UDP : # checking of type of data that was recognized by dpkg
udp = ip.data
print udp.sport
else:
print "Not UDP"