7 IO::Socket - Object interface to socket communications
15 C<IO::Socket> provides an object interface to creating and using sockets. It
16 is built upon the L<IO::Handle> interface and inherits all the methods defined
19 C<IO::Socket> only defines methods for those operations which are common to all
20 types of socket. Operations which are specified to a socket in a particular
21 domain have methods defined in sub classes of C<IO::Socket>
23 C<IO::Socket> will export all functions (and constants) defined by L<Socket>.
31 Creates a C<IO::Socket>, which is a reference to a
32 newly created symbol (see the C<Symbol> package). C<new>
33 optionally takes arguments, these arguments are in key-value pairs.
34 C<new> only looks for one key C<Domain> which tells new which domain
35 the socket it will be. All other arguments will be passed to the
36 configuration method of the package for that domain, See below.
42 See L<perlfunc> for complete descriptions of each of the following
43 supported C<IO::Seekable> methods, which are just front ends for the
44 corresponding built-in functions:
53 peername (getpeername)
54 sockname (getsockname)
56 Some methods take slightly different arguments to those defined in L<perlfunc>
57 in attempt to make the interface more flexible. These are
63 perform the system call C<accept> on the socket and return a new object. The
64 new object will be created in the same class as the listen socket, unless
65 C<PKG> is specified. This object can be used to communicate with the client
66 that was trying to connect. In a scalar context the new socket is returned,
67 or undef upon failure. In an array context a two-element array is returned
68 containing the new socket and the peer address, the list will
69 be empty upon failure.
71 Additional methods that are provided are
75 Set or get the timeout value associated with this socket. If called without
76 any arguments then the current setting is returned. If called with an argument
77 the current setting is changed and the previous value returned.
79 =item sockopt(OPT [, VAL])
81 Unified method to both set and get options in the SOL_SOCKET level. If called
82 with one argument then getsockopt is called, otherwise setsockopt is called.
86 Returns the numerical number for the socket domain type. For example, for
87 a AF_INET socket the value of &AF_INET will be returned.
91 Returns the numerical number for the socket type. For example, for
92 a SOCK_STREAM socket the value of &SOCK_STREAM will be returned.
96 Returns the numerical number for the protocol being used on the socket, if
97 known. If the protocol is unknown, as with an AF_UNIX socket, zero
112 use vars qw(@ISA $VERSION);
115 @ISA = qw(IO::Handle);
121 my $callpkg = caller;
122 Exporter::export 'Socket', $callpkg, @_;
126 my($class,%arg) = @_;
127 my $fh = $class->SUPER::new();
129 ${*$fh}{'io_socket_timeout'} = delete $arg{Timeout};
131 return scalar(%arg) ? $fh->configure(\%arg)
137 sub register_domain {
139 $domain2pkg[$d] = bless \$d, $p;
145 croak "Unsupported socket domain"
146 unless defined $domain2pkg[$domain];
153 my $domain = delete $arg->{Domain};
155 croak 'IO::Socket: Cannot configure a generic socket'
156 unless defined $domain;
158 my $class = ref(_domain2pkg($domain));
160 croak "IO::Socket: Cannot configure socket in domain '$domain'"
161 unless ref($fh) eq "IO::Socket";
168 @_ == 4 or croak 'usage: $fh->socket(DOMAIN, TYPE, PROTOCOL)';
169 my($fh,$domain,$type,$protocol) = @_;
171 if(!defined ${*$fh}{'io_socket_domain'}
172 || !ref(${*$fh}{'io_socket_domain'})
173 || ${${*$fh}{'io_socket_domain'}} != $domain) {
175 ${*$fh}{'io_socket_domain'} = _domain2pkg($domain);
178 socket($fh,$domain,$type,$protocol) or
181 ${*$fh}{'io_socket_type'} = $type;
182 ${*$fh}{'io_socket_proto'} = $protocol;
187 @_ == 4 || croak 'usage: IO::Socket->pair(DOMAIN, TYPE, PROTOCOL)';
188 my($class,$domain,$type,$protocol) = @_;
189 my $fh1 = $class->new();
190 my $fh2 = $class->new();
192 socketpair($fh1,$fh1,$domain,$type,$protocol) or
195 ${*$fh1}{'io_socket_type'} = ${*$fh2}{'io_socket_type'} = $type;
196 ${*$fh1}{'io_socket_proto'} = ${*$fh2}{'io_socket_proto'} = $protocol;
202 @_ == 2 || @_ == 3 or croak 'usage: $fh->connect(NAME) or $fh->connect(PORT, ADDR)';
204 my $addr = @_ == 1 ? shift : sockaddr_in(@_);
205 my $timeout = ${*$fh}{'io_socket_timeout'};
206 local($SIG{ALRM}) = $timeout ? sub { undef $fh; }
207 : $SIG{ALRM} || 'DEFAULT';
210 croak 'connect: Bad address'
211 if(@_ == 2 && !defined $_[1]);
214 defined $Config{d_alarm} && defined alarm($timeout) or
218 my $ok = connect($fh, $addr);
223 croak "connect: timeout"
226 undef $fh unless $ok;
233 @_ == 2 || @_ == 3 or croak 'usage: $fh->bind(NAME) or $fh->bind(PORT, ADDR)';
235 my $addr = @_ == 1 ? shift : sockaddr_in(@_);
237 return bind($fh, $addr) ? $fh
242 @_ >= 1 && @_ <= 2 or croak 'usage: $fh->listen([QUEUE])';
245 unless $queue && $queue > 0;
247 return listen($fh, $queue) ? $fh
252 @_ == 1 || @_ == 2 or croak 'usage $fh->accept([PKG])';
254 my $pkg = shift || $fh;
255 my $timeout = ${*$fh}{'io_socket_timeout'};
256 my $new = $pkg->new(Timeout => $timeout);
262 vec($fdset, $fh->fileno,1) = 1;
263 croak "accept: timeout"
264 unless select($fdset,undef,undef,$timeout);
266 $peer = accept($new,$fh);
269 return wantarray ? defined $peer ? ($new, $peer)
271 : defined $peer ? $new
276 @_ == 1 or croak 'usage: $fh->sockname()';
281 @_ == 1 or croak 'usage: $fh->peername()';
284 || ${*$fh}{'io_socket_peername'}
289 @_ >= 2 && @_ <= 4 or croak 'usage: $fh->send(BUF, [FLAGS, [TO]])';
291 my $flags = $_[2] || 0;
292 my $peer = $_[3] || $fh->peername;
294 croak 'send: Cannot determine peer address'
297 my $r = defined(getpeername($fh))
298 ? send($fh, $_[1], $flags)
299 : send($fh, $_[1], $flags, $peer);
301 # remember who we send to, if it was sucessful
302 ${*$fh}{'io_socket_peername'} = $peer
303 if(@_ == 4 && defined $r);
309 @_ == 3 || @_ == 4 or croak 'usage: $fh->recv(BUF, LEN [, FLAGS])';
312 my $flags = $_[3] || 0;
314 # remember who we recv'd from
315 ${*$sock}{'io_socket_peername'} = recv($sock, $_[1]='', $len, $flags);
320 @_ == 4 or croak '$fh->setsockopt(LEVEL, OPTNAME)';
321 setsockopt($_[0],$_[1],$_[2],$_[3]);
324 my $intsize = length(pack("i",0));
327 @_ == 3 or croak '$fh->getsockopt(LEVEL, OPTNAME)';
328 my $r = getsockopt($_[0],$_[1],$_[2]);
331 if(defined $r && length($r) == $intsize);
337 @_ == 1 ? $fh->getsockopt(SOL_SOCKET,@_)
338 : $fh->setsockopt(SOL_SOCKET,@_);
342 @_ == 1 || @_ == 2 or croak 'usage: $fh->timeout([VALUE])';
344 my $r = ${*$fh}{'io_socket_timeout'} || undef;
346 ${*$fh}{'io_socket_timeout'} = 0 + $val
353 @_ == 1 or croak 'usage: $fh->sockdomain()';
355 ${${*$fh}{'io_socket_domain'}}
359 @_ == 1 or croak 'usage: $fh->socktype()';
361 ${*$fh}{'io_socket_type'}
365 @_ == 1 or croak 'usage: $fh->protocol()';
367 ${*$fh}{'io_socket_protocol'};
378 package IO::Socket::INET;
386 @ISA = qw(IO::Socket);
388 IO::Socket::INET->register_domain( AF_INET );
390 my %socket_type = ( tcp => SOCK_STREAM,
394 =head2 IO::Socket::INET
396 C<IO::Socket::INET> provides a constructor to create an AF_INET domain socket
397 and some related methods. The constructor can take the following options
399 PeerAddr Remote host address <hostname>[:<port>]
400 PeerPort Remote port or service <service>[(<no>)] | <no>
401 LocalAddr Local host bind address hostname[:port]
402 LocalPort Local host bind port <service>[(<no>)] | <no>
403 Proto Protocol name "tcp" | "udp" | ...
404 Type Socket type SOCK_STREAM | SOCK_DGRAM | ...
405 Listen Queue size for listen
406 Reuse Set SO_REUSEADDR before binding
407 Timeout Timeout value for various operations
410 If C<Listen> is defined then a listen socket is created, else if the
411 socket type, which is derived from the protocol, is SOCK_STREAM then
414 The C<PeerAddr> can be a hostname or the IP-address on the
415 "xx.xx.xx.xx" form. The C<PeerPort> can be a number or a symbolic
416 service name. The service name might be followed by a number in
417 parenthesis which is used if the service is not known by the system.
418 The C<PeerPort> specification can also be embedded in the C<PeerAddr>
419 by preceding it with a ":".
421 Only one of C<Type> or C<Proto> needs to be specified, one will be
422 assumed from the other. If you specify a symbolic C<PeerPort> port,
423 then the constructor will try to derive C<Type> and C<Proto> from
428 $sock = IO::Socket::INET->new(PeerAddr => 'www.perl.org',
429 PeerPort => http(80),
432 $sock = IO::Socket::INET->new(PeerAddr => 'localhost:smtp(25)');
434 $sock = IO::Socket::INET->new(Listen => 5,
435 LocalAddr => 'localhost',
445 Return the address part of the sockaddr structure for the socket
449 Return the port number that the socket is using on the local host
453 Return the address part of the sockaddr structure for the socket in a
454 text form xx.xx.xx.xx
458 Return the address part of the sockaddr structure for the socket on
463 Return the port number for the socket on the peer host.
467 Return the address part of the sockaddr structure for the socket on the
468 peer host in a text form xx.xx.xx.xx
475 my($addr,$port,$proto) = @_;
480 if(defined $addr && $addr =~ s,:([\w\(\)/]+)$,,);
483 @proto = $proto =~ m,\D, ? getprotobyname($proto)
484 : getprotobynumber($proto);
486 $proto = $proto[2] || undef;
490 $port =~ s,\((\d+)\)$,,;
492 my $defport = $1 || undef;
493 my $pnum = ($port =~ m,^(\d+)$,)[0];
495 @serv= getservbyname($port, $proto[0] || "")
498 $port = $pnum || $serv[2] || $defport || undef;
500 $proto = (getprotobyname($serv[3]))[2] || undef
504 return ($addr || undef,
512 $@ = join("",ref($fh),": ",@_);
515 if(defined fileno($fh));
521 my($lport,$rport,$laddr,$raddr,$proto,$type);
524 ($laddr,$lport,$proto) = _sock_info($arg->{LocalAddr},
528 $laddr = defined $laddr ? inet_aton($laddr)
531 return _error($fh,"Bad hostname '",$arg->{LocalAddr},"'")
532 unless(defined $laddr);
534 unless(exists $arg->{Listen}) {
535 ($raddr,$rport,$proto) = _sock_info($arg->{PeerAddr},
541 $raddr = inet_aton($raddr);
542 return _error($fh,"Bad hostname '",$arg->{PeerAddr},"'")
543 unless(defined $raddr);
546 return _error($fh,'Cannot determine protocol')
549 my $pname = (getprotobynumber($proto))[0];
550 $type = $arg->{Type} || $socket_type{$pname};
552 my $domain = AF_INET;
553 ${*$fh}{'io_socket_domain'} = bless \$domain;
555 $fh->socket(AF_INET, $type, $proto) or
556 return _error($fh,"$!");
559 $fh->sockopt(SO_REUSEADDR,1) or
563 $fh->bind($lport || 0, $laddr) or
564 return _error($fh,"$!");
566 if(exists $arg->{Listen}) {
567 $fh->listen($arg->{Listen} || 5) or
568 return _error($fh,"$!");
571 return _error($fh,'Cannot determine remote port')
572 unless($rport || $type == SOCK_DGRAM);
574 if($type == SOCK_STREAM || defined $raddr) {
575 return _error($fh,'Bad peer address')
576 unless(defined $raddr);
578 $fh->connect($rport,$raddr) or
579 return _error($fh,"$!");
587 @_ == 1 or croak 'usage: $fh->sockaddr()';
589 (sockaddr_in($fh->sockname))[1];
593 @_ == 1 or croak 'usage: $fh->sockport()';
595 (sockaddr_in($fh->sockname))[0];
599 @_ == 1 or croak 'usage: $fh->sockhost()';
601 inet_ntoa($fh->sockaddr);
605 @_ == 1 or croak 'usage: $fh->peeraddr()';
607 (sockaddr_in($fh->peername))[1];
611 @_ == 1 or croak 'usage: $fh->peerport()';
613 (sockaddr_in($fh->peername))[0];
617 @_ == 1 or croak 'usage: $fh->peerhost()';
619 inet_ntoa($fh->peeraddr);
626 package IO::Socket::UNIX;
629 use vars qw(@ISA $VERSION);
634 @ISA = qw(IO::Socket);
636 IO::Socket::UNIX->register_domain( AF_UNIX );
638 =head2 IO::Socket::UNIX
640 C<IO::Socket::UNIX> provides a constructor to create an AF_UNIX domain socket
641 and some related methods. The constructor can take the following options
643 Type Type of socket (eg SOCK_STREAM or SOCK_DGRAM)
644 Local Path to local fifo
645 Peer Path to peer fifo
646 Listen Create a listen socket
654 Returns the pathname to the fifo at the local end
658 Returns the pathanme to the fifo at the peer end
668 my $type = $arg->{Type} || SOCK_STREAM;
670 my $domain = AF_UNIX;
671 ${*$fh}{'io_socket_domain'} = bless \$domain;
673 $fh->socket(AF_UNIX, $type, 0) or
676 if(exists $arg->{Local}) {
677 my $addr = sockaddr_un($arg->{Local});
681 if(exists $arg->{Listen}) {
682 $fh->listen($arg->{Listen} || 5) or
685 elsif(exists $arg->{Peer}) {
686 my $addr = sockaddr_un($arg->{Peer});
687 $fh->connect($addr) or
695 @_ == 1 or croak 'usage: $fh->hostpath()';
696 my $n = $_[0]->sockname || return undef;
697 (sockaddr_un($n))[0];
701 @_ == 1 or croak 'usage: $fh->peerpath()';
702 my $n = $_[0]->peername || return undef;
703 (sockaddr_un($n))[0];
708 L<Socket>, L<IO::Handle>
712 Graham Barr E<lt>F<Graham.Barr@tiuk.ti.com>E<gt>
716 Copyright (c) 1995 Graham Barr. All rights reserved. This program is free
717 software; you can redistribute it and/or modify it under the same terms
722 1; # Keep require happy