xarex has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,

I have the following piece of code that acts as a listing server for data.

The data is Binary data, but for some reason its displaying in ASCII, is it possible to write the data in its raw format to a file, or display it on the screen?
Or is it possible to convert this data to HEX format?
#!/usr/bin/perl -w use strict; use IO::Socket; my( $sock, $r_msg, $in_msg, $inhost, $MAXLEN, $PORTNO ); $MAXLEN = 10240; $PORTNO = 7780; $sock = IO::Socket::INET->new( LocalPort => $PORTNO, Proto => 'udp' ) or die "socket: $@"; print "Awaiting UDP messages on port $PORTNO\n"; $r_msg = "Received OK."; while ($sock->recv($in_msg, $MAXLEN)) { my($port, $ipaddr) = sockaddr_in($sock->peername); $inhost = gethostbyaddr($ipaddr, AF_INET); no utf8; print "Client $inhost said $in_msg\n"; # print sprintf("%04x",$in_msg)."\n"; use bytes; print length($in_msg)."\n"; $sock->send($r_msg); } die "recv: $!";
the above produces:
Client 41-208-48-1.xxxxxx.x.x said àêc':_è@âäçä-ó
50
Any help will be great

Kenny<br<

Replies are listed 'Best First'.
Re: UDP Server Binary Data
by Fletch (Bishop) on Nov 23, 2007 at 16:04 UTC

    Not a Perl solution per se, but presuming you have sufficient resources and/or network-fu to run it a tool like wireshark will let you see everything that's going across the wire both ways (to and from your port) with a nice hexdump / od style display of the contents.

    Update: And if you really want to do this in your code the source to the perl implementation of od from ppt may be of interest.

Re: UDP Server Binary Data
by ikegami (Patriarch) on Nov 23, 2007 at 18:07 UTC
    • Is it possible to write the data in its raw format to a file?

      Yes. You already are. You might want to binmode the file handles from which you read and to which you write.

    • Is it possible to display the data in its raw format on the screen?

      No, bytes don't have appearance. Binary data means "a series of bytes, usually not meant for human understanding", so its raw format is a series of bytes. What would you expect a series of bytes to look like? You can see chairs, tables and desks, but a byte?

      Whatever your answer is, your answer is simply a means of *representation* bytes and not actually seeing bytes themselves. You asked Perl (by using treating the bytes as a string) to display them as characters. You could display the bytes as a sequence of hex numbers instead, but that's not going to change what's being stored. You'll have to pick a representation. Perhaps the output generated by this code I wrote will satisfy your needs.