tags:

views:

329

answers:

2

I am writing a Perl program that sends and receives messages from two sockets and acta as a switch. I have to modify the received messages received from one socket, prepend 3 bytes to the data, and finally send the modified messages to another socket. I adopt select()...sysread()...syswrite() mechanism to poll for messages between sockets. The received messages are stored in $buffer during modification.

Now I can use following way to get the received messages:

my $hexmsg = unpack("H*", $buffer);
my @msg = ( $hexmsg =~ m/../g );

then I can insert 3 bytes to @msg. However, I don't know how to pack the message in @msg into a scalar(such as $buffer) and send it to another socket by syswrite(). Can anybody help me? Thank you in advance!

BTW, are messages in $buffer binary?

+1  A: 

If you've used unpack to get the data from $buffer, have you tried using pack to put the data back in there?

Dave Webb
This has the benefit of using almost the exact same code both ways, as far as I remember. I could be wrong, though - pack() and unpack() are my current weak-points in Perl.
Chris Lutz
I tried my $shexmsg=join("",@msg);$buffer=pack("X",$shexmsg);where "X" denotes template of pack, such as "n*", "b*","u*". However, all failed... I don't know what to do...
bonny
+3  A: 

Yes, messages in $buffer are binary (if I'm guessing what you mean by that correctly). If your only reason for unpacking it into @msg is to insert the bytes, don't. Use substr instead, and just write out the changed $buffer. For instance:

substr( $buffer, 0, 0, "\x01\x02\x03" ); # insert 3 bytes at beginning.

If you are doing other things with @msg, you could continue to use that as well as doing the substr insert before writing it out, or you could use substr or pack or split or vec or a regex to parse out the pieces you need. You'd need to describe what you are doing to get more specific help.

ysth
Besides inserting 3 bytes to $buffer, I also need to identify the header and body of the message.What should I do? Can substr() still work?
bonny
Finally I use @msg to analyze messages and insert 3 bytes into $buffer for specific messages.I think using substr($buffer,<start>,<offset>) can get specific info of message for analysis(for example msg type is denoted by 1 byte), but I didn't try this way.
bonny
By the way, if I also want to modify the first two bytes of $buffer,what should I do? Because the first two bytes of $buffer denotes the length of the message,and after inserting 3 bytes to the message, the message length also should be changed accordingly.
bonny