简体   繁体   中英

How to get raw (un-decoded) byte arrays from a TCPSocket in Ruby

I've been using ruby to setup a TCPSocket with a server and I've hit a snag. When receiving data from the socket (with either a socket.gets or a socket.recv ) I get something like this:

x00\x03!\xB2\x00\x00*\xCF

What I get when I capture the packets in Wireshark is

x00\x03\x21\xB2\x00\x00\x2a\xCF

As you can see, the \\x21 is decoded into the ASCII equivalent ! and the \\x2a is decoded into the ASCII equivalent * .

I've checked and googled a ton of times and have not yet found a solution to get the raw, un-decoded information. I have a parser built that will search for the relevant data from the stream and grab what I need, but I don't want to have to waste time re-encoding it before I have to decode it. Or, I incorporate ASCII into my parser, but that would be a huge pain. There is a lot of bytes in this stream and to re-encode them all would be time consuming. I also see that netcat returns the same output from the TCP stream that ruby does. I could not figure out how to get netcat to output the un-decoded byte arrays either.

Code:

require 'socket'
s = TCPSocket.new "10.0.0.3", 27000

while true do
  item = s.recv(5000)
  puts item
  puts item.inspect
end

This is my first foray into socket programming, so I apologize if I missed something very obvious.

I kind of invented the problem in my head, I am dumb.

To solve this, all you need to do is take the string of TCP information and call unpack("H*") on it like this:

"x00\x03!\xB2\x00\x00*\xCF".unpack("H*")
=> ["7830300321b200002acf"]

Which is exactly like x00\\x03\\x21\\xB2\\x00\\x00\\x2a\\xCF

Now I just need to adjust my parser to split it or deal with the big clump of byte arrays

More info on unpack

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM