ConfusedAboutCPP
ConfusedAboutCPP

Reputation: 603

python / dpkt: Find out if packet is a tcp packet or a udp packet ,

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()

Upvotes: 11

Views: 26376

Answers (2)

A python script that captures the packets on the ethernet adapter eth0 using dpkt, and differentiates between TCP and UDP packets of the IP.

import dpkt
import pcapy

cap=pcapy.open_live('eth0',100000,1,0)
(header,payload)=cap.next()

while header:
    eth=dpkt.ethernet.Ethernet(str(payload))

    # Check whether IP packets: to consider only IP packets 
    if eth.type!=dpkt.ethernet.ETH_TYPE_IP:
            continue
            # Skip if it is not an IP packet
    ip=eth.data
    if ip.p==dpkt.ip.IP_PROTO_TCP: # Check for TCP packets
           TCP=ip.data 
           # ADD TCP packets Analysis code here
    elif ip.p==dpkt.ip.IP_PROTO_UDP: # Check for UDP packets
           UDP=ip.data 
           # UDP packets Analysis code here

    (header,payload)=cap.next()

Upvotes: 10

Zuljin
Zuljin

Reputation: 2640

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"

Upvotes: 11

Related Questions