Python

 

 

 

 

Python - Decoding IPv4 Header

 

NOTE 1 : All the examples in this page are written in Python 3.x. It may not work if you use Pyton 2.x

NOTE 2 : All the examples in this page are assumed to be written/run on Windows 7 unless specifically mentioned. You MAY (or may not) need to modify the syntax a little bit if you are running on other operating system.

 

Example 01 > ========================================================

 

This example will show you the very simple and straightfoward way to decode IPv6 header. This example is designed for getting familiar with structure of IPv6 header and number/string manipulation in Python. I don't think this is very efficient code, but it would be very simple/easy to understand.

For simplicity, I gave a precaptured IPv6 byte array to decode. But if you can combine the skills explained in Raw Packet : IPv4 page, you can modify the code so that the script can decode IPv6 header directly from a network card.

 

The purpose of this example is to decode Byte Array marked in Red in the wireshark log shown below. Compare the program output with Wireshark log.

 

 

If you understand only a few Python syntax, you would be able to read the code directly. Followings are some syntax you may refer to if you have difficulties understanding this code.

 

# Following is the source code for this example.  Understanding this code is very simple.

 

import binascii

 

def decodeIPv4Header(pktBytes) :

    

    headerLength = 20

    headerBytes = pktBytes[0:headerLength]

    headerInt = int.from_bytes(headerBytes, 'big')

    headerBin = '{0:0{1}b}'.format(headerInt,headerLength*8)

    #print("Header in Binary = ",headerBin)

 

    print("IPv4 Header ==============================================")

    version = int(headerBin[0:4],2)

    print("Version : ",version)

 

    ihl = int(headerBin[4:8],2)

    print("Header Length : ",ihl * 4,"(Bytes)")

 

    dscp = int(headerBin[8:14],2)

    print("DSCP (Differentiated Services Code Point) : ",headerBin[8:14],"(Bin)")

 

    ecn = int(headerBin[14:16],2)

    print("ECN(Explicit Congestion Notification) : ",headerBin[14:16],"(Bin)")

 

    totalLength = int(headerBin[16:32],2)

    print("Total Length : ",totalLength,"(Dec) :", totalLength)

 

    identification = int(headerBin[32*1:32*1+16],2)

    print("Identification : ",'{0:#x}'.format(identification),"(Hex),", identification,"(Dec)")

 

    flags = int(headerBin[32*1+16:32*1+18],2)

    print("flags : ",headerBin[32*1+16:32*1+18],"(Bin)")

 

    fragmentOffset = int(headerBin[32*1+19:32*1+32],2)

    print("Fragment Offset : ",fragmentOffset,"(Dec)")

 

    ttl = int(headerBin[32*2:32*2+8],2)

    print("Time To Live (TTL) : ",ttl,"(Dec)")

 

    protocol = int(headerBin[32*2+8:32*2+16],2)

    print("Protocol : ",protocol,"(Dec) : ", ProtocolKeyword(protocol))

    

    checkSum = int(headerBin[32*2+16:32*2+32],2)

    print("Header Checksum : ",'{0:#x}'.format(checkSum),"(Hex)")

    

    srcAddString = '{0:d}'.format(int(headerBin[3*32:3*32+8],2))

    srcAddString = srcAddString + "." + '{0:d}'.format(int(headerBin[3*32+8:3*32+16],2))

    srcAddString = srcAddString + "." + '{0:d}'.format(int(headerBin[3*32+16:3*32+24],2))

    srcAddString = srcAddString + "." + '{0:d}'.format(int(headerBin[3*32+24:3*32+32],2))

    print("Source : ",srcAddString)

    

    dstAddString = '{0:d}'.format(int(headerBin[4*32:4*32+8],2))

    dstAddString = dstAddString + "." + '{0:d}'.format(int(headerBin[4*32+8:4*32+16],2))

    dstAddString = dstAddString + "." + '{0:d}'.format(int(headerBin[4*32+16:4*32+24],2))

    dstAddString = dstAddString + "." + '{0:d}'.format(int(headerBin[4*32+24:4*32+32],2))

    print("Destination : ",dstAddString)

 

    payloadLen = len(pktBytes)-(ihl * 4)

 

    return payloadLen,protocol

 

def ProtocolKeyword(protocolIndex):

    switcher = {

        0:"HOPOPT", #IPv6 Hop-by-Hop Option

        1: "ICMP", #Internet Control Message Protocol

        2: "IGMP", #Internet Group Management Protocol

        3: "GGP", #Gateway-to-Gateway Protocol

        4: "IP-in-IP", #IP in IP (encapsulation)

        5: "ST", #Internet Stream Protocol

        6: "TCP", #Transmission Control Protocol

        7: "CBT", #Core-based trees

        8: "EGP", #Exterior Gateway Protocol

        9: "IGP", #Interior Gateway Protocol (any private interior gateway (used by Cisco for their IGRP))

        10: "BBN-RCC-MON", #BBN RCC Monitoring

        11: "NVP-II", #Network Voice Protocol

        12: "PUP", #Xerox PUP

        13: "ARGUS", #ARGUS

        14: "EMCON", #EMCON

        15: "XNET", #Cross Net Debugger

        16: "CHAOS", #Chaos

        17: "UDP", #User Datagram Protocol

        18: "MUX", #Multiplexing

        19: "DCN-MEAS", #DCN Measurement Subsystems

        20: "HMP", #Host Monitoring Protocol

        21: "PRM", #Packet Radio Measurement

        22: "XNS-IDP", #XEROX NS IDP

        23: "TRUNK-1", #Trunk-1

        24: "TRUNK-2", #Trunk-2

        25: "LEAF-1", #Leaf-1

        26: "LEAF-2", #Leaf-2

        27: "RDP", #Reliable Datagram Protocol

        28: "IRTP", #Internet Reliable Transaction Protocol

        29: "ISO-TP4", #ISO Transport Protocol Class 4

        30: "NETBLT", #Bulk Data Transfer Protocol

        31: "MFE-NSP", #MFE Network Services Protocol

        32: "MERIT-INP", #MERIT Internodal Protocol

        33: "DCCP", #Datagram Congestion Control Protocol

        34: "3PC", #Third Party Connect Protocol

        35: "IDPR", #Inter-Domain Policy Routing Protocol

        36: "XTP", #Xpress Transport Protocol

        37: "DDP", #Datagram Delivery Protocol

        38: "IDPR-CMTP", #IDPR Control Message Transport Protocol

        39: "TP++", #TP++ Transport Protocol

        40: "IL", #IL Transport Protocol

        41: "IPv6", #IPv6 Encapsulation

        42: "SDRP", #Source Demand Routing Protocol

        43: "IPv6-Route", #Routing Header for IPv6

        44: "IPv6-Frag", #Fragment Header for IPv6

        45: "IDRP", #Inter-Domain Routing Protocol

        46: "RSVP", #Resource Reservation Protocol

        47: "GRE", #Generic Routing Encapsulation

        48: "MHRP", #Mobile Host Routing Protocol

        49: "BNA", #BNA

        50: "ESP", #Encapsulating Security Payload

        51: "AH", #Authentication Header

        52: "I-NLSP", #Integrated Net Layer Security Protocol

        53: "SWIPE", #SwIPe

        54: "NARP", #NBMA Address Resolution Protocol

        55: "MOBILE", #IP Mobility (Min Encap)

        56: "TLSP", #Transport Layer Security Protocol (using Kryptonet key management)

        57: "SKIP", #Simple Key-Management for Internet Protocol

        58: "IPv6-ICMP", #ICMP for IPv6

        59: "IPv6-NoNxt", #No Next Header for IPv6

        60: "IPv6-Opts", #Destination Options for IPv6

        62: "CFTP", #CFTP

        64: "SAT-EXPAK", #SATNET and Backroom EXPAK

        65: "KRYPTOLAN", #Kryptolan

        66: "RVD", #MIT Remote Virtual Disk Protocol

        67: "IPPC", #Internet Pluribus Packet Core

        69: "SAT-MON", #SATNET Monitoring

        70: "VISA", #VISA Protocol

        71: "IPCU", #Internet Packet Core Utility

        72: "CPNX", #Computer Protocol Network Executive

        73: "CPHB", #Computer Protocol Heart Beat

        74: "WSN", #Wang Span Network

        75: "PVP", #Packet Video Protocol

        76: "BR-SAT-MON", #Backroom SATNET Monitoring

        77: "SUN-ND", #SUN ND PROTOCOL-Temporary

        78: "WB-MON", #WIDEBAND Monitoring

        79: "WB-EXPAK", #WIDEBAND EXPAK

        80: "ISO-IP", #International Organization for Standardization Internet Protocol

        81: "VMTP", #Versatile Message Transaction Protocol

        82: "SECURE-VMTP", #Secure Versatile Message Transaction Protocol

        83: "VINES", #VINES

        84: "TTP", #TTP

        84: "IPTM", #Internet Protocol Traffic Manager

        85: "NSFNET-IGP", #NSFNET-IGP

        86: "DGP", #Dissimilar Gateway Protocol

        87: "TCF", #TCF

        88: "EIGRP", #EIGRP

        89: "OSPF", #Open Shortest Path First

        90: "Sprite-RPC", #Sprite RPC Protocol

        91: "LARP", #Locus Address Resolution Protocol

        92: "MTP", #Multicast Transport Protocol

        93: "AX.25", #AX.25

        94: "IPIP", #IP-within-IP Encapsulation Protocol

        95: "MICP", #Mobile Internetworking Control Protocol

        96: "SCC-SP", #Semaphore Communications Sec. Pro

        97: "ETHERIP", #Ethernet-within-IP Encapsulation

        98: "ENCAP", #Encapsulation Header

        99: "*", #Any private encryption scheme

        100: "GMTP", #GMTP

        101: "IFMP", #Ipsilon Flow Management Protocol

        102: "PNNI", #PNNI over IP

        103: "PIM", #Protocol Independent Multicast

        104: "ARIS", #IBM's ARIS (Aggregate Route IP Switching) Protocol

        105: "SCPS", #SCPS (Space Communications Protocol Standards)

        106: "QNX", #QNX

        107: "A/N", #Active Networks

        108: "IPComp", #IP Payload Compression Protocol

        109: "SNP", #Sitara Networks Protocol

        110: "Compaq-Peer", #Compaq Peer Protocol

        111: "IPX-in-IP", #IPX in IP

        112: "VRRP", #Virtual Router Redundancy Protocol, Common Address Redundancy Protocol (not IANA assigned)

        113: "PGM", #PGM Reliable Transport Protocol

        114: "*", #Any 0-hop protocol

        115: "L2TP", #Layer Two Tunneling Protocol Version 3

        116: "DDX", #D-II Data Exchange (DDX)

        117: "IATP", #Interactive Agent Transfer Protocol

        118: "STP", #Schedule Transfer Protocol

        119: "SRP", #SpectraLink Radio Protocol

        120: "UTI", #Universal Transport Interface Protocol

        121: "SMP", #Simple Message Protocol

        122: "SM", #Simple Multicast Protocol

        123: "PTP", #Performance Transparency Protocol

        124: "IS-IS over IPv4", #Intermediate System to Intermediate System (IS-IS) Protocol over IPv4

        125: "FIRE", #Flexible Intra-AS Routing Environment

        126: "CRTP", #Combat Radio Transport Protocol

        127: "CRUDP", #Combat Radio User Datagram

        128: "SSCOPMCE", #Service-Specific Connection-Oriented Protocol in a Multilink and Connectionless Environment

        129: "IPLT",

        130: "SPS", #Secure Packet Shield

        131: "PIPE", #Private IP Encapsulation within IP

        132: "SCTP", #Stream Control Transmission Protocol

        133: "FC", #Fibre Channel

        134: "RSVP-E2E-IGNORE", #Reservation Protocol (RSVP) End-to-End Ignore

        135: "Mobility Header", #Mobility Extension Header for IPv6

        136: "UDPLite", #Lightweight User Datagram Protocol

        137: "MPLS-in-IP", #Multiprotocol Label Switching Encapsulated in IP

        138: "manet", #MANET Protocols

        139: "HIP", #Host Identity Protocol

        140: "Shim6", #Site Multihoming by IPv6 Intermediation

        141: "WESP", #Wrapped Encapsulating Security Payload

        142: "ROHC", #Robust Header Compression

    }

    return switcher.get(protocolIndex, "nothing")

        

# Beginning of Main Routine

ByteAry = b'\x45\x00\x00\x3C\x58\x87\x00\x00\x80\x01\x5E\xAA\xC0\xA8\x01\x1F\xC0\xA8\x01\x20\x08\x00\x4D\x5A

\x00\x01\x00\x01\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6A\x6B\x6C\x6D\x6E\x6F\x70\x71\x72\x73\x74\x75\x76\x77

\x61\x62\x63\x64\x65\x66\x67\x68\x69'

 

HexStr=binascii.b2a_hex(ByteAry)

 

if((ByteAry[0] & 0xF0) == 0x40) :

   payloadLength,protocol = decodeIPv4Header(ByteAry)

else :

   print("The packet given is not IPv4 header")

 

 

Result :----------------------------------------------------------------

 

IPv4 Header ==============================================

Version :  4

Header Length :  20 (Bytes)

DSCP (Differentiated Services Code Point) :  000000 (Bin)

ECN(Explicit Congestion Notification) :  00 (Bin)

Total Length :  60 (Dec) : 60

Identification :  0x5887 (Hex), 22663 (Dec)

flags :  00 (Bin)

Fragment Offset :  0 (Dec)

Time To Live (TTL) :  128 (Dec)

Protocol :  1 (Dec) :  ICMP

Header Checksum :  0x5eaa (Hex)

Source :  192.168.1.31

Destination :  192.168.1.32