473,395 Members | 1,418 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

manipulating hex values

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
Apr 1 '08 #1
1 7181
On 2008-04-01, Stephen Cattaneo <st**************@u4eatech.comwrote:
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
That's a hex represenation of a literal integer object. The
object itself isn't either decimal or hex. It's and integer
object. [It's _probably_ stored in binary, but that's beside
the point.]
2. as a string - "\x55aa"
That is the string "Uaa". Perhaps you meant "\x55\xaa"? If
so, that might or might not have the same bit-pattern as
0x55aa depending on what CPU you're using.
If I want to convert hex to decimal I can use: int("\x55aa", 16)
No you can't'

1) That call doesn't convert hex to decimal. It converts to
an integer object (which almost certainly is stored in 2's
compliment binary). There is nothing in decimal in the
example.

2) "\x55aa" doesn't mean what you think it does. "\x55aa" is
a three byte string consisting of a byte with the value
0x55 and then two ascii 'a' bytes. 0x55 is an ascii 'U'.

I think you meant "0x55aa". That's completely different
from either "\x55aa" or "\x55\xaa".
# note that plain 0x55aa, instead of "\x55aa", will
raise an exception
That's because the above function call requires a string.
0x55aa isn't a string. It's an integer literal. "\x55aa" is a
three byte string that's equal to "Uaa", and it can't be
converted to an integer.
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.
First: stop talking (and thinking) about "decimal" stuff.
You're not really doing anything in decimal in any of the code
you've posted so far.
In my bellow code I get
"""byteList.append(int(value,16))
ValueError: invalid literal for int()"""
when attempting to run.
No you don't. You get this:

Traceback (most recent call last):
File "foo.py", line 20, in ?
checksum = calcIPChecksum(["\x45" + "\x00", "\x01\x4a", "\x00\x00", "\x40"+"\x00", "\x20"+"\x11"])
NameError: name 'calcIPChecksum' is not defined

Don't re-type examples in postings. Paste in the actual code
that you're using. That way we don't have to try to guess
about the differences between the real code and what's in the
posting.
I do not understand why this exception is being raised?
If you want to understand why you're getting that exception,
add the line "print value" immediately prior to the
int(value,16) line.
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"])
You pretty much lost me on the above algorithm
(hex/decimal/string/integer mixups aside).

FWIW, here's an IP checksum routine:

def calcIPCheckSum(ipHeaders):
total = 0
for w in ipHeaders:
total += w
carries = total >16
sum = (total + carries) & 0xffff
return sum ^ 0xffff

print hex(calcIPCheckSum([0x0100,0xf203,0xf4f5,0xf6f7]))
A slightly more terse version:

import operator
def calcIPCheckSum(ipHeaders):
total = reduce(operator.add,ipHeaders)
carries = total >16
return ((total + carries) ^ 0xffff) & 0xffff
--
Grant Edwards grante Yow! ... he dominates the
at DECADENT SUBWAY SCENE.
visi.com
Apr 1 '08 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Michael J. Astrauskas | last post by:
Does anyone have a function for manipulating GET variables in a URL? I want to be able to modify some parameters without affecting others. An example of what I'm looking for: Let's say the...
10
by: Bart Van der Donck | last post by:
Hello, I have a table, say ---------- ID|myvalue ---------- 1|B 2|C 3|A
10
by: Kristian Nybo | last post by:
Hi, I'm writing a simple image file exporter as part of a school project. To implement my image format of choice I need to work with big-endian bytes, where 'byte' of course means '8 bits', not...
1
by: Robin Tucker | last post by:
Hi, I have one stored procedure that calls another ( EXEC proc_abcd ). I would like to return a result set (a temporary table I have created in the procedure proc_abcd) to the calling procedure...
6
by: Tom Rowton | last post by:
This one has me a bit confused and I'm not finding what I need in the MSDN or by searching these forums, so here goes... I have a rather large, complex code-in-page WebForm (don't ask) and a...
5
by: darrel | last post by:
(apologies if I've asked this before in here...I thought I had, but can't seem to find my original post). I'm trying to automate the process of picking some colors. I want to select one color,...
3
by: Ken Fine | last post by:
I'm interested in programmatically manipulating groups of ASP.NET controls by type. Can someone suggest code for the following? Loop through, say, all label controls on a page, and assigning a...
5
by: Carlo Gambino | last post by:
I'm trying to manipulate strings of user input data, using ord() to assign the decimal value to each character in the string. I can return the values, but need to understand the best way to store the...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.