3 # Copyright (c) 1996 Graham Barr <Graham.Barr@tiuk.ti.com>. All rights
4 # reserved. This program is free software; you can redistribute it and/or
5 # modify it under the same terms as Perl itself.
11 IO::Socket - Object interface to socket communications
19 C<IO::Socket> provides an object interface to creating and using sockets. It
20 is built upon the L<IO::Handle> interface and inherits all the methods defined
23 C<IO::Socket> only defines methods for those operations which are common to all
24 types of socket. Operations which are specified to a socket in a particular
25 domain have methods defined in sub classes of C<IO::Socket>
27 C<IO::Socket> will export all functions (and constants) defined by L<Socket>.
35 Creates an C<IO::Socket>, which is a reference to a
36 newly created symbol (see the C<Symbol> package). C<new>
37 optionally takes arguments, these arguments are in key-value pairs.
38 C<new> only looks for one key C<Domain> which tells new which domain
39 the socket will be in. All other arguments will be passed to the
40 configuration method of the package for that domain, See below.
42 C<IO::Socket>s will be in autoflush mode after creation.
48 See L<perlfunc> for complete descriptions of each of the following
49 supported C<IO::Socket> methods, which are just front ends for the
50 corresponding built-in functions:
59 peername (getpeername)
60 sockname (getsockname)
62 Some methods take slightly different arguments to those defined in L<perlfunc>
63 in attempt to make the interface more flexible. These are
69 perform the system call C<accept> on the socket and return a new object. The
70 new object will be created in the same class as the listen socket, unless
71 C<PKG> is specified. This object can be used to communicate with the client
72 that was trying to connect. In a scalar context the new socket is returned,
73 or undef upon failure. In an array context a two-element array is returned
74 containing the new socket and the peer address, the list will
75 be empty upon failure.
77 Additional methods that are provided are
81 Set or get the timeout value associated with this socket. If called without
82 any arguments then the current setting is returned. If called with an argument
83 the current setting is changed and the previous value returned.
85 =item sockopt(OPT [, VAL])
87 Unified method to both set and get options in the SOL_SOCKET level. If called
88 with one argument then getsockopt is called, otherwise setsockopt is called.
92 Returns the numerical number for the socket domain type. For example, for
93 a AF_INET socket the value of &AF_INET will be returned.
97 Returns the numerical number for the socket type. For example, for
98 a SOCK_STREAM socket the value of &SOCK_STREAM will be returned.
102 Returns the numerical number for the protocol being used on the socket, if
103 known. If the protocol is unknown, as with an AF_UNIX socket, zero
118 use vars qw(@ISA $VERSION);
121 @ISA = qw(IO::Handle);
127 my $callpkg = caller;
128 Exporter::export 'Socket', $callpkg, @_;
132 my($class,%arg) = @_;
133 my $fh = $class->SUPER::new();
136 ${*$fh}{'io_socket_timeout'} = delete $arg{Timeout};
138 return scalar(%arg) ? $fh->configure(\%arg)
144 sub register_domain {
146 $domain2pkg[$d] = $p;
151 my $domain = delete $arg->{Domain};
153 croak 'IO::Socket: Cannot configure a generic socket'
154 unless defined $domain;
156 croak "IO::Socket: Unsupported socket domain"
157 unless defined $domain2pkg[$domain];
159 croak "IO::Socket: Cannot configure socket in domain '$domain'"
160 unless ref($fh) eq "IO::Socket";
162 bless($fh, $domain2pkg[$domain]);
163 $fh->configure($arg);
167 @_ == 4 or croak 'usage: $fh->socket(DOMAIN, TYPE, PROTOCOL)';
168 my($fh,$domain,$type,$protocol) = @_;
170 socket($fh,$domain,$type,$protocol) or
173 ${*$fh}{'io_socket_domain'} = $domain;
174 ${*$fh}{'io_socket_type'} = $type;
175 ${*$fh}{'io_socket_proto'} = $protocol;
181 @_ == 4 || croak 'usage: IO::Socket->pair(DOMAIN, TYPE, PROTOCOL)';
182 my($class,$domain,$type,$protocol) = @_;
183 my $fh1 = $class->new();
184 my $fh2 = $class->new();
186 socketpair($fh1,$fh1,$domain,$type,$protocol) or
189 ${*$fh1}{'io_socket_type'} = ${*$fh2}{'io_socket_type'} = $type;
190 ${*$fh1}{'io_socket_proto'} = ${*$fh2}{'io_socket_proto'} = $protocol;
196 @_ == 2 || @_ == 3 or croak 'usage: $fh->connect(NAME) or $fh->connect(PORT, ADDR)';
198 my $addr = @_ == 1 ? shift : sockaddr_in(@_);
199 my $timeout = ${*$fh}{'io_socket_timeout'};
200 local($SIG{ALRM}) = $timeout ? sub { undef $fh; }
201 : $SIG{ALRM} || 'DEFAULT';
204 croak 'connect: Bad address'
205 if(@_ == 2 && !defined $_[1]);
208 defined $Config{d_alarm} && defined alarm($timeout) or
212 my $ok = connect($fh, $addr);
217 croak "connect: timeout"
220 undef $fh unless $ok;
227 @_ == 2 || @_ == 3 or croak 'usage: $fh->bind(NAME) or $fh->bind(PORT, ADDR)';
229 my $addr = @_ == 1 ? shift : sockaddr_in(@_);
231 return bind($fh, $addr) ? $fh
236 @_ >= 1 && @_ <= 2 or croak 'usage: $fh->listen([QUEUE])';
239 unless $queue && $queue > 0;
241 return listen($fh, $queue) ? $fh
246 @_ == 1 || @_ == 2 or croak 'usage $fh->accept([PKG])';
248 my $pkg = shift || $fh;
249 my $timeout = ${*$fh}{'io_socket_timeout'};
250 my $new = $pkg->new(Timeout => $timeout);
256 vec($fdset, $fh->fileno,1) = 1;
257 croak "accept: timeout"
258 unless select($fdset,undef,undef,$timeout);
260 $peer = accept($new,$fh);
263 return wantarray ? defined $peer ? ($new, $peer)
265 : defined $peer ? $new
270 @_ == 1 or croak 'usage: $fh->sockname()';
275 @_ == 1 or croak 'usage: $fh->peername()';
278 || ${*$fh}{'io_socket_peername'}
283 @_ >= 2 && @_ <= 4 or croak 'usage: $fh->send(BUF, [FLAGS, [TO]])';
285 my $flags = $_[2] || 0;
286 my $peer = $_[3] || $fh->peername;
288 croak 'send: Cannot determine peer address'
291 my $r = defined(getpeername($fh))
292 ? send($fh, $_[1], $flags)
293 : send($fh, $_[1], $flags, $peer);
295 # remember who we send to, if it was sucessful
296 ${*$fh}{'io_socket_peername'} = $peer
297 if(@_ == 4 && defined $r);
303 @_ == 3 || @_ == 4 or croak 'usage: $fh->recv(BUF, LEN [, FLAGS])';
306 my $flags = $_[3] || 0;
308 # remember who we recv'd from
309 ${*$sock}{'io_socket_peername'} = recv($sock, $_[1]='', $len, $flags);
314 @_ == 4 or croak '$fh->setsockopt(LEVEL, OPTNAME)';
315 setsockopt($_[0],$_[1],$_[2],$_[3]);
318 my $intsize = length(pack("i",0));
321 @_ == 3 or croak '$fh->getsockopt(LEVEL, OPTNAME)';
322 my $r = getsockopt($_[0],$_[1],$_[2]);
325 if(defined $r && length($r) == $intsize);
331 @_ == 1 ? $fh->getsockopt(SOL_SOCKET,@_)
332 : $fh->setsockopt(SOL_SOCKET,@_);
336 @_ == 1 || @_ == 2 or croak 'usage: $fh->timeout([VALUE])';
338 my $r = ${*$fh}{'io_socket_timeout'} || undef;
340 ${*$fh}{'io_socket_timeout'} = 0 + $val
347 @_ == 1 or croak 'usage: $fh->sockdomain()';
349 ${*$fh}{'io_socket_domain'};
353 @_ == 1 or croak 'usage: $fh->socktype()';
355 ${*$fh}{'io_socket_type'}
359 @_ == 1 or croak 'usage: $fh->protocol()';
361 ${*$fh}{'io_socket_protocol'};
372 package IO::Socket::INET;
380 @ISA = qw(IO::Socket);
382 IO::Socket::INET->register_domain( AF_INET );
384 my %socket_type = ( tcp => SOCK_STREAM,
389 =head2 IO::Socket::INET
391 C<IO::Socket::INET> provides a constructor to create an AF_INET domain socket
392 and some related methods. The constructor can take the following options
394 PeerAddr Remote host address <hostname>[:<port>]
395 PeerPort Remote port or service <service>[(<no>)] | <no>
396 LocalAddr Local host bind address hostname[:port]
397 LocalPort Local host bind port <service>[(<no>)] | <no>
398 Proto Protocol name (or number) "tcp" | "udp" | ...
399 Type Socket type SOCK_STREAM | SOCK_DGRAM | ...
400 Listen Queue size for listen
401 Reuse Set SO_REUSEADDR before binding
402 Timeout Timeout value for various operations
405 If C<Listen> is defined then a listen socket is created, else if the
406 socket type, which is derived from the protocol, is SOCK_STREAM then
409 The C<PeerAddr> can be a hostname or the IP-address on the
410 "xx.xx.xx.xx" form. The C<PeerPort> can be a number or a symbolic
411 service name. The service name might be followed by a number in
412 parenthesis which is used if the service is not known by the system.
413 The C<PeerPort> specification can also be embedded in the C<PeerAddr>
414 by preceding it with a ":".
416 If C<Proto> is not given and you specify a symbolic C<PeerPort> port,
417 then the constructor will try to derive C<Proto> from the service
418 name. As a last resort C<Proto> "tcp" is assumed. The C<Type>
419 parameter will be deduced from C<Proto> if not specified.
421 If the constructor is only passed a single argument, it is assumed to
422 be a C<PeerAddr> specification.
426 $sock = IO::Socket::INET->new(PeerAddr => 'www.perl.org',
427 PeerPort => 'http(80)',
430 $sock = IO::Socket::INET->new(PeerAddr => 'localhost:smtp(25)');
432 $sock = IO::Socket::INET->new(Listen => 5,
433 LocalAddr => 'localhost',
437 $sock = IO::Socket::INET->new('127.0.0.1:25');
446 Return the address part of the sockaddr structure for the socket
450 Return the port number that the socket is using on the local host
454 Return the address part of the sockaddr structure for the socket in a
455 text form xx.xx.xx.xx
459 Return the address part of the sockaddr structure for the socket on
464 Return the port number for the socket on the peer host.
468 Return the address part of the sockaddr structure for the socket on the
469 peer host in a text form xx.xx.xx.xx
478 unshift(@_, "PeerAddr") if @_ == 1;
479 return $class->SUPER::new(@_);
483 my($addr,$port,$proto) = @_;
488 if(defined $addr && $addr =~ s,:([\w\(\)/]+)$,,);
491 @proto = $proto =~ m,\D, ? getprotobyname($proto)
492 : getprotobynumber($proto);
494 $proto = $proto[2] || undef;
498 $port =~ s,\((\d+)\)$,,;
500 my $defport = $1 || undef;
501 my $pnum = ($port =~ m,^(\d+)$,)[0];
503 @serv= getservbyname($port, $proto[0] || "")
506 $port = $pnum || $serv[2] || $defport || undef;
508 $proto = (getprotobyname($serv[3]))[2] || undef
512 return ($addr || undef,
520 $@ = join("",ref($fh),": ",@_);
523 if(defined fileno($fh));
529 my($lport,$rport,$laddr,$raddr,$proto,$type);
532 ($laddr,$lport,$proto) = _sock_info($arg->{LocalAddr},
536 $laddr = defined $laddr ? inet_aton($laddr)
539 return _error($fh,"Bad hostname '",$arg->{LocalAddr},"'")
540 unless(defined $laddr);
542 unless(exists $arg->{Listen}) {
543 ($raddr,$rport,$proto) = _sock_info($arg->{PeerAddr},
549 $raddr = inet_aton($raddr);
550 return _error($fh,"Bad hostname '",$arg->{PeerAddr},"'")
551 unless(defined $raddr);
554 $proto ||= (getprotobyname "tcp")[2];
555 return _error($fh,'Cannot determine protocol')
558 my $pname = (getprotobynumber($proto))[0];
559 $type = $arg->{Type} || $socket_type{$pname};
561 $fh->socket(AF_INET, $type, $proto) or
562 return _error($fh,"$!");
565 $fh->sockopt(SO_REUSEADDR,1) or
569 $fh->bind($lport || 0, $laddr) or
570 return _error($fh,"$!");
572 if(exists $arg->{Listen}) {
573 $fh->listen($arg->{Listen} || 5) or
574 return _error($fh,"$!");
577 return _error($fh,'Cannot determine remote port')
578 unless($rport || $type == SOCK_DGRAM || $type == SOCK_RAW);
580 if($type == SOCK_STREAM || defined $raddr) {
581 return _error($fh,'Bad peer address')
582 unless(defined $raddr);
584 $fh->connect($rport,$raddr) or
585 return _error($fh,"$!");
593 @_ == 1 or croak 'usage: $fh->sockaddr()';
595 (sockaddr_in($fh->sockname))[1];
599 @_ == 1 or croak 'usage: $fh->sockport()';
601 (sockaddr_in($fh->sockname))[0];
605 @_ == 1 or croak 'usage: $fh->sockhost()';
607 inet_ntoa($fh->sockaddr);
611 @_ == 1 or croak 'usage: $fh->peeraddr()';
613 (sockaddr_in($fh->peername))[1];
617 @_ == 1 or croak 'usage: $fh->peerport()';
619 (sockaddr_in($fh->peername))[0];
623 @_ == 1 or croak 'usage: $fh->peerhost()';
625 inet_ntoa($fh->peeraddr);
632 package IO::Socket::UNIX;
635 use vars qw(@ISA $VERSION);
640 @ISA = qw(IO::Socket);
642 IO::Socket::UNIX->register_domain( AF_UNIX );
644 =head2 IO::Socket::UNIX
646 C<IO::Socket::UNIX> provides a constructor to create an AF_UNIX domain socket
647 and some related methods. The constructor can take the following options
649 Type Type of socket (eg SOCK_STREAM or SOCK_DGRAM)
650 Local Path to local fifo
651 Peer Path to peer fifo
652 Listen Create a listen socket
660 Returns the pathname to the fifo at the local end
664 Returns the pathanme to the fifo at the peer end
674 my $type = $arg->{Type} || SOCK_STREAM;
676 $fh->socket(AF_UNIX, $type, 0) or
679 if(exists $arg->{Local}) {
680 my $addr = sockaddr_un($arg->{Local});
684 if(exists $arg->{Listen}) {
685 $fh->listen($arg->{Listen} || 5) or
688 elsif(exists $arg->{Peer}) {
689 my $addr = sockaddr_un($arg->{Peer});
690 $fh->connect($addr) or
698 @_ == 1 or croak 'usage: $fh->hostpath()';
699 my $n = $_[0]->sockname || return undef;
700 (sockaddr_un($n))[0];
704 @_ == 1 or croak 'usage: $fh->peerpath()';
705 my $n = $_[0]->peername || return undef;
706 (sockaddr_un($n))[0];
711 L<Socket>, L<IO::Handle>
715 Graham Barr E<lt>F<Graham.Barr@tiuk.ti.com>E<gt>
719 Copyright (c) 1996 Graham Barr. All rights reserved. This program is free
720 software; you can redistribute it and/or modify it under the same terms
725 1; # Keep require happy