perl pack与unpack函数的例子

发布时间:2021-01-03编辑:脚本学堂
本文分享一例perl使用pack与unpack函数的应用实例,学习下perl中pack与unpack函数的用法,有需要的朋友可以参考下。

本节内容:
 perl pack与unpack函数的应用实例

例子:
 

复制代码 代码示例:

#!/usr/bin/perl
#site: www.jb200.com
# setsockopt -> recv timeout, man setsockopt and man 7 socket
$sock->sockopt(SO_RCVTIMEO, pack("I2", 1, 0));
#
# sendmsg.pl
# test for my monitor server app

use IO::Socket;
use Time::HiRes qw(usleep);

sub open_sock {
    my ($host, $port) = @_;
    my $socket = IO::Socket::INET->new(PeerAddr => $host,
                                       PeerPort => $port,
                                       Proto    => "tcp",
                                       Type     => SOCK_STREAM)
        or die "couldn't connect to $host:$port :$@n";
}

sub send_msg {
    my $socket = shift @_;

    # specify the struct of message head
    my $msg_head_packfmt = "CCn";
    my $msg_head_size = 4;  # (C + C + n) == 4

    # read the argument and pack
    my ($type, $stat, $data) = @_;
    my $size = length($data);
    my $package = pack("${msg_head_packfmt}a*", $type, $stat, $size, $data);

    # send the package to server
    print $socket $package;
}

sub recv_msg {
    my $socket = shift @_;

    # specify the struct of message head
    my $msg_head_packfmt = "CCn";
    my $msg_head_size = 4;  # (C + C + n) == 4

    # receive a respond package
    recv($socket, $answer, $msg_head_size, $flags);
    my ($type, $stat, $size) = unpack($msg_head_packfmt, $answer);
    my $data;
    recv($socket, $data, $size, flags);

    return ($type, $stat, $size, $data);
}

sub xtest {
    my ($type, $stat, $data, $host, $port) = @_;

    my $sock = open_sock($host, $port);

    send_msg $sock, $type, $stat, $data;

    my $size;
    ($type, $stat, $size, $data) = recv_msg $sock;

    if ($data eq "OK") {
        printf "OK!!!n";
    } else {
        printf "NG!!!n";
    }

    printf "the package info: $type $stat $sizen$datan";
    close($sock);
    usleep(1000 * 500);  # sleep 500 ms (0.5s)
}

my ($remote_host, $remore_port) = ("10.4.0.11", "1111");

xtest 0, 0, "detect", $remote_host, $remore_port;

xtest 1, 0, "ls *.c", $remote_host, $remore_port;

xtest 2, 0, "kkk kkk", $remote_host, $remore_port;