manipulating hex values

Discussion in 'Python' started by Stephen Cattaneo, Apr 1, 2008.

  1. 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
     
    Stephen Cattaneo, Apr 1, 2008
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. darrel

    manipulating hex in ASP.net

    darrel, Oct 6, 2005, in forum: ASP .Net
    Replies:
    2
    Views:
    2,717
    S. Justin Gengo
    Oct 6, 2005
  2. darrel

    manipulating hex values

    darrel, Mar 1, 2006, in forum: ASP .Net
    Replies:
    5
    Views:
    567
    Kevin Spencer
    Mar 3, 2006
  3. Replies:
    10
    Views:
    6,229
    Neredbojias
    Aug 19, 2005
  4. Bengt Richter
    Replies:
    6
    Views:
    474
    Juha Autero
    Aug 19, 2003
  5. Stephen Cattaneo

    Re: Re: manipulating hex values

    Stephen Cattaneo, Apr 1, 2008, in forum: Python
    Replies:
    1
    Views:
    551
    Stephen Cattaneo
    Apr 3, 2008
Loading...

Share This Page