socket send query

Peter Hansen peter at engcorp.com
Wed Feb 18 20:02:41 CET 2004


connections cardiff wrote:
> 
> if i send the hex data values with a socket send then python assumes i
> am trying to send a string of ascii characters and when i look at what
> was sent in the sniffer i see the data i sent has been coverted into
> their corresponding hex values.  I want python to leave it alone and
> send it.
> 
> i guess if my hex values had acsii equivalents i could send them and
> they would be converted to the data i want but i dont think all my hex
> data has acsii equivalents..
> 
> is there another way i should be doing this?

It sounds to me like you have a string with two characters per byte
of intended data, where those characters are the digits in the hex
representation of the data.  For example '45CE123F'.  Is that right?

If that's the case, you are probably looking for the binascii module
and specifically its unhexlify() method.  For example:

>>> import binascii
>>> binascii.unhexlify('45CE123F')
'E\xce\x12?'
>>> len(_)        # _ means last result in an interactive session
4

As you can see, the original 8-byte string with "hex" in it has
resulted in four bytes of actual data.

Another approach is to store your data as integers in a list, then
convert to a string:

>>> d = [0x45, 0xce, 0x12, 0x3f]
>>> d
[69, 206, 18, 63]
>>> ''.join([chr(x) for x in d])
'E\xce\x12?'

As you can see, the same results as before but without starting with
a string containing the hex representation of the data.

> PS.  IN CASE YOU DIDNT NOTICE I AM A NEWBIE!

In that case, always consider posting small actual snippets of the
code you are trying to write, to provide useful context and help
give an idea at what level the responses should be targetted.

-Peter



More information about the Python-list mailing list