manipulating hex values

Stephen Cattaneo stephen.cattaneo at u4eatech.com
Tue Apr 1 21:09:09 CEST 2008


Gabriel Genellina wrote:
> <div class="moz-text-flowed" style="font-family: -moz-fixed">En Tue, 
> 01 Apr 2008 14:11:31 -0300, Stephen Cattaneo 
> <stephen.cattaneo at u4eatech.com> escribió:
>
>> I am relatively new to socket programming.  I am attempting to use raw
>> sockets to spoof my IP address.
>
> Don't bother to try...
>
?   Is there a better solution to spoofing my IP then using raw sockets 
(I'm working on a machine with multiple interfaces and need to be able 
to some how specify which interface that traffic needs to be 
sent/recieved to/from)
>> 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"
>
> The later is exactly the same string as "Uaa":
>
> py> print "\x55aa"
> Uaa
>
>> 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
>
> Have you tried it?
>
> py> int("\x55aa", 16)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> ValueError: invalid literal for int() with base 16: 'Uaa'
> py> int("0x55aa", 16)
> 21930
>
An oversight on my part and the source of my problem. Thank you.

The source of my confusion is that I need to keep my bytes formated 
correctly.   I am using the below  'raw socket example' proof-of-concept 
code as my example.  (And yes, I have tried the proof-of-concept.  It 
works correctly.  It is not my code.)
dstAddr = "\x01\x02\x03\x04\x05\x06" 
dstAddr1 = "0x010203040506"
dstAddr != dstAddr1

Follow up question:  What is the best to store my bytes up until sending 
the packets?  Perhaps I should use lists of decimal numbers and then 
before sending convert to hex. 
I.E. dstAddr = [ 1, 2, 3, 4, 5, 6]
dstAddr.prepareToSend()
txFrame = struct.pack("!6s6sh",dstAddr,srcAddr,proto) + ethData

Is there a better way to do this?

Thanks,

Steve


----------------raw socket example-------------------
#!/usr/bin/python

import sys
import string
import struct
from socket import *

proto = 0x55aa
s = socket(AF_PACKET, SOCK_RAW, proto)
s.bind(("eth0",proto))

ifName,ifProto,pktType,hwType,hwAddr = s.getsockname()
srcAddr = hwAddr
# send packet to ethernet MAC: 01-02-03-04-05-06
dstAddr = "\x01\x02\x03\x04\x05\x06"
ethData = "here is some data for an ethernet packet"
print "ethData length is: " + str(len(ethData))

txFrame = struct.pack("!6s6sh",dstAddr,srcAddr,proto) + ethData          
s.send(txFrame)




More information about the Python-list mailing list