0

I want to send a file on a socket, and need to pass its length in the first four bytes.

Here is what I want to do in C:

struct { int lenght; //four bytes char msg[40]; }dataBuf; write(fd, &databuf, sizeof(dataBuf)) 

How do I push an integer onto a socket, so it receives it as an integer at other end, not as an ASCII value?

I don't want to hardcode it like "\x04\X03" and I tried to do it with pack(L*). That only works with array and I don't have a way to break my four byte integer into a four byte array.

1

2 Answers 2

4

Try putting the integer into an array and then using pack. For example:

socket.write( [0xffff].pack("L") ) 
Sign up to request clarification or add additional context in comments.

Comments

1

Look at the BinData gem.

Your example might look like this:

class DataBuf < BinData::Record uint32 :length array :msg, :initial_length => 40 do uint8 end end io = File.open(...) r = DataBuf.read(io) puts "Data buffer is #{r.length} length and it has '#{r.msg}' message" 

I'm not sure about message, you should look at the String section of BinData documentation.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.