By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,561 Members | 3,265 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,561 IT Pros & Developers. It's quick & easy.

how to send an int over a socket

P: n/a
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
Jul 18 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Tom Brown <br***@esteem.com> writes:
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?

str(123)

'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.
Jul 18 '05 #2

P: n/a
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
Jul 18 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.