pythonic malloc

Brad Hards bhards at bigpond.net.au
Mon Jul 21 06:32:08 EDT 2003


Karl Scalet wrote:

> kjockey schrieb:
>> I have some simple UDP code that does:
>>
s.sendto("\xf0\x00\x02\x00rachel\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",addr)
>> 
>> This is OK, except that I'd like to change the text in the middle
>> ("rachel", which is the hostname FWIW), and the NUL padding needs to go
>> out to make the length 25 bytes (so the padding depends on the length of
>> the name).
>> 
>> So I could do something like:
>> retpacket = "\xf0\x00\x02\x00"+socket.gethostname()
>> while len(retpacket) < 26:
> 
> shouldn't that be 25?
Yes.

>>      retpacket += "\x00"
>> s.sendto(retpacket, addr)
>> 
>> But that feels "wrong". And Python in a Nutshell says its a bad idea  -
>> "anti-idiom".
>> 
>> Can anyone show me the true path?
> 
> No idea, if it's the true path:
> 
> hn = socket.gethostname()
> retpacket = '\xf0\x00\x02\x00%s%s' % (hn, (25-4-len(hn))*chr(0))
> s.sendto(retpacket, addr)
Probably better for efficiency, but not much for readability....

Anyone else?




More information about the Python-list mailing list