write hex to socket, weird

C

c|sc0

Hi,

I just want to write raw data to a socket (by using IO::Socket)
All I want to do is the following:

print $my_socket "\x0f\xa1\x02.....and much more here";

A part of the data is actually an IP address
so in my case if I want to send "10.1.2.3" I should send "\x0a\01\x02\x3"

I tried to create a sub() to generate the "\x0a\01\x02\x3" out of
"10.1.2.3", but I failed.

Obviously the following does not work:

$code .= "\\x" . substr( unpack("H*", pack("N*", $my_byte)) , -2 ,2);

I tried many more ways but still can't achieve it.
I'd like to do such a sub() for "string" as well

e.g "ABC" should give "\x41\x42\x43"
but as you already understood, i dont want the string "\x41\x42\x43" but
the actually value behind it.

Can you guys give a tip ?

thanks
C|sc0-
 
G

Greg Bacon

: [...]
:
: I tried to create a sub() to generate the "\x0a\01\x02\x3" out of
: "10.1.2.3", but I failed.
:
: Obviously the following does not work:
:
: $code .= "\\x" . substr( unpack("H*", pack("N*", $my_byte)) , -2 ,2);

Do the hosts on the ends of your connection have different byte orders?

Here's a rough start:

% cat try
#! /usr/bin/perl

use warnings;
use strict;

sub ip2hex {
join '' => map chr($_) => split /\./, shift;
}

for (split //, ip2hex '10.1.2.3') {
printf "%02x\n", ord($_);
}
% ./try
0a
01
02
03

: [...]

Hope this helps,
Greg
 
J

John W. Krahn

c|sc0 said:
I just want to write raw data to a socket (by using IO::Socket)
All I want to do is the following:

print $my_socket "\x0f\xa1\x02.....and much more here";

A part of the data is actually an IP address
so in my case if I want to send "10.1.2.3" I should send "\x0a\01\x02\x3"

I tried to create a sub() to generate the "\x0a\01\x02\x3" out of
"10.1.2.3", but I failed.

Use inet_aton() from the modules Socket or IO::Socket.

perldoc Socket

Obviously the following does not work:

$code .= "\\x" . substr( unpack("H*", pack("N*", $my_byte)) , -2 ,2);

I tried many more ways but still can't achieve it.
I'd like to do such a sub() for "string" as well

e.g "ABC" should give "\x41\x42\x43"
but as you already understood, i dont want the string "\x41\x42\x43" but
the actually value behind it.

"ABC" and "\x41\x42\x43" contain exactly the same data:

$ perl -le'print "\x41\x42\x43"'
ABC
$ perl -le'$x = "\x41\x42\x43"; $y = "ABC"; print "True" if $x eq $y'
True


If you need to expand "ABC" to "\x41\x42\x43":

$ perl -le'$x = q(ABC); $x =~ s/(.)/ sprintf q(\x%x), ord $1 /ges; print
$x'
\x41\x42\x43



John
 

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

Forum statistics

Threads
474,293
Messages
2,571,505
Members
48,193
Latest member
DannyRober

Latest Threads

Top