bokr at oz.net
Tue Jul 22 01:22:46 CEST 2003
On Mon, 21 Jul 2003 10:32:08 GMT, Brad Hards <bhards at bigpond.net.au> wrote:
>Karl Scalet wrote:
>> kjockey schrieb:
>>> I have some simple UDP code that does:
>>> 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?
>>> retpacket += "\x00"
>>> s.sendto(retpacket, addr)
>>> But that feels "wrong". And Python in a Nutshell says its a bad idea -
Well, adding the same character one by one is about as ugly as
sum = 14
while sum <25:
sum += 1
(Of course, if the original 14 units are also the same, as in integers,
sum += 25-sum
is not much better ;-)
But for small strings, I don't think it should be a big deal to do something like
retpacket = "\xf0\x00\x02\x00"+socket.gethostname()
retpacket += '\x00'*(25-len(retpacket))
>>> 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....
another alternative (untested!):
fmt = '\xf0\x00\x02\x00%s'+21*'\x00' # or write it out ;-)
retpacket = (fmt%socket.gethostname())[:25]
More information about the Python-list