blib/lib/UDPmsg.pm untested

filter: Statementstmt 0.0% 0 / 45 Branchbran 0.0% 0 / 8 Conditioncond 0.0% 0 / 11 MC/DCmcdc 0.0% 0 / 6 Subroutinesub 0.0% 0 / 6 Podpod 0.0% 0 / 5 totaltotal 0.0% 0 / 81 CC 5 SCAR 23.0
CC
5
Cov
0%
read
20.0
canread
6.0
new
2.0
CRAP 10.0
1 # IPC::UDPmsg.pm
2
3 package IPC::UDPmsg;
4 use Socket;
5
6
7 # new takes a single parm: the port# we will listen on
8 sub new {
9 shift; # first parm is package name
10 my $port = shift; # get the number of the port we listen on
11 my $self = {}; # create an empty object
12 my $proto = getprotobyname('udp') || die "getprotobyname: cannot get proto : $!";
13 $self->{PORT} = $port;
14 $self->{IADDR} = Socket::inet_aton('127.0.0.1');
15 socket($self->{SOCK}, AF_INET, SOCK_DGRAM, $proto) || die "socket: $!";
16 my $servaddr = Socket::sockaddr_in( $port, $self->{IADDR} );
17 bind($self->{SOCK}, $servaddr ) || die "bind: $!";
18 bless $self;
19 return $self;
20 }
21
22
23 # read will return a packet, if available, or undef. read is non-blocking
24 sub read {
25 my $self = shift;
26 if( $self->canread() == 0 ) {
27 return undef;
28 }
29 my $message;
30 my $from = recv ($self->{SOCK}, $message, 320, 0);
31 my $i = $! + 0;
32 if( $! && $i != 10054 ) {
33 die "error receiving message: $i $!\n";
34 }
35 if( $i == 10054 ) { return undef; }
36 my ($p, $adr) = Socket::sockaddr_in( $from );
37 $self->{FROM} = $p;
38 return $message;
39 }
40
41
42 # canread will test to see if a packet is available. return >0 if yes
43 sub canread {
44 my $self = shift;
45 my ($rin, $win, $ein) = ('','','');
46 vec($rin, fileno($self->{SOCK}), 1 ) = 1;
47 $ein = $rin | $win;
48 my $i = select( $rin, $win, $ein, 0);
49 if( $i < 0 ) {
50 my $j = $! + 0;
51 print "error receiving message: $j $!\n";
52 next;
53 }
54 return $i;
55 }
56
57
58 # write will send a packet to another process, the parm is the port to send the packet to
59 sub write {
60 my $self = shift;
61 my $port = shift;
62 my $xmsg = shift;
63 my $servaddr = Socket::sockaddr_in($port, $self->{IADDR} );
64 send ($self->{SOCK}, $xmsg, 0, $servaddr) || die "error sending message: $!";
65 }
66
67
68 # from return the port number of who sent the last read packet
69 sub from {
70 my $self = shift;
71 return $self->{FROM};
72 }
73 1;
74
75
76 __END__