[Tutor] packet parsing

Remco Gerlich scarblac@pino.selwerd.nl
Thu, 28 Feb 2002 21:57:19 +0100


On  0, python@jayed.com wrote:
> My second question is: how do I look at/manipulate bytes of an incoming
> network packet?  Or bits even.  Right now, I have the following piece of 
> code that receives the SSH server's initial key exchange packet:
> 
>     kexrecv = mysock.recv(blocksize) 
> 
> I want to directly manipulate the bits/bytes of kexrecv.  Everything
> that I've done makes kexrecv into a string.  And I'm having problems
> with kexrecv as a string -- I want to deal with it as a binary stream.

The string *is* the binary stream. A string is just a bunch of bytes.

> type(kexrecv) results in <type 'str'>
> type(`kexrecv`) results in <type 'str'>
> len(kexrecv) returns nothing
> len(`kexrecv`) returns 830
> print len(kexrecv) returns 632
> print len(`kexrecv`) returns 830
> 
> (Yes, I know that the backticks are equivalent to repr() -- I looked it
> up on google last night).  I want to deal with kexrecv and not
> `kexrecv`.  But I haven't been able to figure it out.
> 
> If kexrecv is a string [as type(kexrecv) seems to think] why doesn't
> len(kexrecv) return anything?  And if kexrecv is a string, why does
> len(`kexrecv`) return a larger value than "print len(kexrecv)"?

kexrecv is a string of length 632.

`kexrecv` is its text representation, in a way that it could be a python
literal - that means that say a zero byte is one character in the string
itself, but '\x00' in the repr - three bytes longer. Try playing around with
the string (and small parts of it) a bit more in the interpreter to get the
idea.

I don't have more time atm to reply carefully to your other comments, this
is just a quick post.

-- 
Remco Gerlich