how to send an int over a socket

T

Tom Brown

Hi,

I have what seems to be a simple problem. But I can not for the life of me
find a way to send an integer over a socket. The send method will only accept
strings. Here is what I am trying to do:

testmessage = 'test message'
msglen = len(testmessage)
sock.send(msglen)
sock.send(testmessage)

Now, I know I can do this:

testmessage = 'test message'
sock.send('\xC') # send hard coded length of testmessage in hex in string
sock.send(testmessage)

However, in my actual program I will not know the length of testmessage in
advance. So how do I convert msglen into a suitable format for the send
method?

Thanks,
Tom
 
P

Paul Rubin

Tom Brown said:
However, in my actual program I will not know the length of testmessage in
advance. So how do I convert msglen into a suitable format for the send
method?
'123'

You might also look at

http://cr.yp.to/proto/netstrings.txt

which describes some issues you should pay attention to, and suggests
a standardized format.
 
P

Pierre Quentel

Use string formatting :

msglen = '%16s' %len(testmessage)

will return a 16-byte string, beginning with spaces. Send it over your
connection and use int() to get the message length

Pierre
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,020
Latest member
GenesisGai

Latest Threads

Top