manipulating hex values

Stephen Cattaneo stephen.cattaneo at u4eatech.com
Tue Apr 1 19:11:31 CEST 2008


Hi all,

I am relatively new to socket programming.  I am attempting to use raw 
sockets to spoof my IP address.  From what I can tell I will have to 
build from the Ethernet layer on up.   This is fine, but I am having 
some trouble with manipulating my hex values. 

 Seems to me that there are two ways to store hex values:
1. as literal hex - 0x55aa
2. as a string - "\x55aa"

If I want to convert hex to decimal I can use:
int("\x55aa", 16)  # note that plain 0x55aa, instead of "\x55aa", will 
raise an exception

The Question:
If I want to do any kind of calculation I have found its best to just 
convert my values to decimal, do the math, then convert back to hex.  In 
my bellow code I get
"""byteList.append(int(value,16))
ValueError: invalid literal for int()"""
when attempting to run.   I do not understand why this exception is 
being raised?  It is a for loop iterating over a list of hex strings.  
Sorry for the long-ish question.  Any help or comments would be appreciated.


----my checksum---
def calcIPCheckSum(ipHeaders):
   byteList = []
   # convert groups from hex to dec
   for value in ipHeaders:
     byteList.append(int(value,16))  # Exception raised here!
      
   # 1's compliment
   for index in range(len(byteList)): 
      byteList[index] = abs(byteList[index] - 65535)
     
   # add bytes together shifting the extra byte
   total = 0
   for value in byteList:
      total = total + value
      if total > 65535:
         total = total - 65535
        
   return hex(total)

checksum = calcIPChecksum(["\x45" + "\x00", "\x01\x4a", "\x00\x00", 
"\x40"+"\x00", "\x20"+"\x11"])
-------------------------

Cheers,

Steve



More information about the Python-list mailing list