![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
use Net::Gen;
Net::Gen
module provides basic services for handling socket-based communications. It
supports no particular protocol family directly, however, so it is of
direct use primarily to implementors of other modules. To this end, several
housekeeping functions are provided for the use of derived classes, as well
as several inheritable methods.
Also provided in this distribution are Net::Inet
, Net::TCP
,
Net::UDP
, and Net::UNIX
, which are layered atop Net::Gen
.
$obj = Net::Gen->new($classname); $obj = Net::Gen->new($classname, \%parameters);
Returns a newly-initialised object of the given class. If called for a
class other than Net::Gen
, no validation of the supplied parameters will be performed. (This is so
that the derived class can add the parameter validation it needs to the
object before allowing validation.)
$obj = $classname->new_from_fh(*FH); $obj = $classname->new_from_fh(\*FH); $obj = $classname->new_from_fh(fileno($fh));
Returns a newly-initialised object of the given class, open on a newly-dup()ed copy of the given filehandle or file descriptor. As many of the standard object parameters as possible will be determined from the passed filehandle. This is determined (in part) by calling the corresponding new, init, and getsockinfo methods for the new object.
Only real filehandles or file descriptor numbers are allowed as arguments. This method makes no attempt to resolve filehandle names.
return undef unless $self->init;
Verifies that all previous parameter assignments are valid (via
checkparams). Returns the incoming object on success, and
undef
on failure. This method is normally called from the new
method appropriate to the class of the created object.
$ok = $obj->checkparams;
Verifies that all previous parameter assignments are valid. (Normally called only via the init method, rather than directly.)
$ok = $obj->setparams(\%newparams, $newonly, $checkup); $ok = $obj->setparams(\%newparams, $newonly); $ok = $obj->setparams(\%newparams);
Sets new parameters from the given hashref, with validation. This is done
in a loop over the key, value pairs from the
newparams
parameter. The precise nature of the validation depends on the $newonly
and $checkup
parameters (which are optional), but in all cases the keys to be set are
checked against those registered with the object. If the $newonly
parameter is negative, the value from the hashref will only be set if there
is not already a defined value associated with that key, but skipping the
setting of the value is silent. If the
$newonly
parameter is not negative or if there is no existing defined value, if the $checkup
parameter is false then the setting of the new value is skipped if the new
value is identical to the old value. If those checks don't cause the
setting of a new value to be skipped, then if the $newonly
parameter is positive and there is already a defined value for the
specified key, a warning will be issued and the new value will not be set.
If none of the above checks cause the setting of a new value to be skipped, but if the specified key has a validation routine, that routine will be called with the given object, the current key, and the proposed new value as parameters. It is allowed for the validation routine to alter the new-value argument to change what will be set. (This is useful when changing a hostname to be in canonical form, for example.) If the validation routine returns a non-null string, that will be used to issue a warning, and the new value will not be set. If the validation routine returns a null string (or if there is no validation routine), the new value will (finally) get set for the given key.
The setparams method returns 1 if all parameters were successfully set, and undef
otherwise.
$ok = $obj->setparam($key, $value, $newonly, $checkup); $ok = $obj->setparam($key, $value, $newonly); $ok = $obj->setparam($key, $value);
Sets a single new parameter. Uses the setparams method, and has the same rules for the handling of the $newonly
and
$checkup
parameters. Returns 1 if the set was successful, and
undef
otherwise.
$ok = $obj->delparams(\@keynames);
Removes the settings for the specified parameters. Uses the
setparams method (with undef
for the values) to validate that the removal is allowed by the owning
object. If the invocation of setparams is successful, then the parameters in question are removed. Returns 1 if
all the removals were successful, and undef
otherwise.
$ok = $obj->delparam($keyname);
Sugar-coated call to the delparams method. Functions just like it.
%hash = $obj->getparams(\@keynames, $noundefs); %hash = $obj->getparams(\@keynames);
Returns a hash (not a reference) consisting of the key-value pairs corresponding to the
specified keyname list. Only those keys which exist in the current
parameter list of the object will be returned. If the $noundefs
parameter is present and true, then existing keys with undefined values
will be suppressed like non-existent keys.
$value = $obj->getparam($key, $defval, $def_if_undef); $value = $obj->getparam($key, $defval); $value = $obj->getparam($key);
Returns the current setting for the named parameter (in the current
object), or the specified default value if the parameter is not in the
object's current parameter list. If the optional
$def_if_undef
parameter is true, then undefined values will be treated the same as
non-existent keys, and thus will return the supplied default value ($defval
).
$ok = $obj->open;
Makes a call to the socket()
builtin, using the current object
parameters to determine the desired protocol family, socket type, and
protocol number. If the object was already open, its
stopio method will be called before socket()
is called again. The
object parameters consulted (and possibly updated) are PF,
AF, proto, and type. Returns true if the socket()
call results in an open
filehandle, undef
otherwise.
$obj->condition;
(Re-)establishes the condition of the associated filehandle after an
open()
or accept().
Sets the socket to be
autoflushed and marks it binmode().
No useful value is
returned.
$ok = $obj->listen($maxqueue); $ok = $obj->listen;
Makes a call to the listen()
builtin on the filehandle
associated with the object. Propagates the return value from
listen().
If the $maxqueue parameter is missing, it defaults to the value of the object's maxq parameter, or the value of SOMAXCONN
. If the SOMAXCONN
constant is not available in your configuration, the default value used for
the listen method is 5. This method will fail if the object is not bound and cannot be
made bound by a simple call to its bind method.
$ok = $obj->bind;
Makes a call to the bind()
builtin on the filehandle
associated with the object. The arguments to bind()
are
determined from the current parameters of the object. First, if the
filehandle has previously been bound or connected, it is closed. Then, if
it is not currently open, a call to the open method is made. If all that works (which may be a no-op), then the
following list of possible values is tried for the bind()
builtin: First, the
srcaddrlist object parameter, if its value is an array reference. The elements of the
array are tried in order until a bind()
succeeds or the list
is exhausted. Second, if the
srcaddrlist parameter is not set to an array reference, if the
srcaddr parameter is a non-null string, it will be used. Finally, if neither srcaddrlist nor srcaddr is suitably set, the AF parameter will be used to construct a sockaddr
struct which will be mostly zeroed, and the bind()
will be
attempted with that. If the bind()
fails, undef
will be returned at this point. Otherwise, a call to the getsockinfo
method will be made, and then the value from a call to the
isbound method will be returned.
If all that seems too confusing, don't worry. Most clients will never need to do an explicit bind call, anyway. If you're writing a server or a privileged client which does need to bind to a particular local port or address, and you didn't understand the foregoing discussion, you may be in trouble. Don't panic until you've checked the discussion of binding in the derived class you're using, however.
$obj->unbind;
Removes any saved binding for the object. Unless the object is currently connected, this will result in a call to its close method, in order to ensure that any previous binding is removed. Even if the object is connected, the srcaddrlist object parameter is removed (via the object's delparams method). The return value from this method is indeterminate.
$ok = $obj->connect;
Attempts to establish a connection for the object. First, if the object is
currently connected or has been connected since the last time it was
opened, its close method is called. Then, if the object is not currently open, its open method is called. If it's not open after that, undef
is returned. If it is open, and if either of its srcaddrlist or srcaddr
parameters are set to indicate that a bind()
is desired, and
it is not currently bound, its bind method is called. If the
bind method is called and fails, undef
is returned. (Most of the foregoing is a no-op for simple clients, so don't
panic.)
Next, if the dstaddrlist object parameter is set to an array reference, a call to
connect()
is made for each element of the list until it
succeeds or the list is exhausted. If the
dstaddrlist parameter is not an array reference, a single attempt is made to call
connect()
with the dstaddr object parameter. If no connect()
call succeeded, undef
is returned. Finally, a call is made to the object's getsockinfo method, and then the value from a call to its isconnected method is returned.
Note that the derived classes tend to provide additional capabilities which make the connect method easier to use than the above description would indicate.
($localsockaddr, $peersockaddr) = $obj->getsockinfo; $peersockaddr = $obj->getsockinfo;
Attempts to determine connection parameters associated with the object. If
a getsockname()
call on the associated filehandle succeeds,
the srcaddr object parameter is set to that returned sockaddr. If a
getpeername()
call on the associated filehandle succeeds, the dstaddr parameter is set to that returned sockaddr. In a scalar context, if both
socket addresses were found, the getpeername()
value is
returned, otherwise undef
is returned. In a list context, the getsockname()
and
getpeername()
values are returned, unless both are undefined.
Derived classes normally replace this method with one which provides friendlier return information appropriate to the derived class, and which establishes more of the object parameters.
$ok = $obj->shutdown($how); $ok = $obj->shutdown;
Calls the shutdown()
builtin on the filehandle associated with
the object. This method is a no-op, returning 1, if the filehandle is not
connected. The $how
parameter is as per the shutdown()
builtin, which in turn
should be as described in the shutdown(2)
manpage. If the $how
parameter is not present, it is assumed to be 2.
Returns 1 if nothing to do, otherwise propagates the return from the
shutdown()
builtin.
$ok = $obj->stopio;
Calls the close()
builtin on the filehandle associated with
the object, unless that filehandle is already closed. Returns 1 or the
return value from the close()
builtin. This method is
primarily for the use of server modules which need to avoid
shutdown calls at inappropriate times. This method calls the
delparams method for the keys of srcaddr and dstaddr.
$ok = $obj->close;
The close method is like a call to the shutdown method followed by a call to the stopio method. It is the standard way to close down an object.
$ok = $obj->send($buffer, $flags); $ok = $obj->send($buffer);
This method calls the send()
builtin (three-argument form).
The
$flags
parameter is defaulted to 0 if not supplied. The return value from the
send()
builtin is returned. This method makes no attempt to
trap SIGPIPE
.
$ok = $obj->sendto($buffer, $destsockaddr, $flags); $ok = $obj->sendto($buffer, $destsockaddr);
This method calls the send()
builtin (four-argument form). The
$flags
parameter is defaulted to 0 if not supplied. The return value from the
send()
builtin is returned. This method makes no attempt to
trap SIGPIPE
.
$ok = $obj->SEND($buffer, $flags, $destsockaddr); $ok = $obj->SEND($buffer, $flags); $ok = $obj->SEND($buffer);
This method calls the send()
builtin (three- or four-argument
form). The $flags
parameter is defaulted to 0 if not supplied. If the $destsockaddr
value is missing or undefined, the three- argument form of the
send()
builtin will be used. A defined
$destsockaddr
will result in a four-argument send()
call. The return value
from the send()
builtin is returned. This method makes no
attempt to trap SIGPIPE
.
$ok = $obj->put(@whatever); $ok = put $obj @whatever;
This method uses the print()
builtin to send the
@whatever
arguments to the filehandle associated with the
object. That filehandle is always marked for autoflushing by the open
method, so the method is in effect equivalent to this:
$ok = $obj->send(join($, , @whatever) . $\ , 0);
However, since multiple fwrite()
calls are sometimes involved
in the actual use of print(),
this method can be more
efficient than the above code sample for large strings in the argument
list. It's a bad idea except on stream sockets (SOCK_STREAM
) though, since the record boundaries are unpredictable through stdio. This
method makes no attempt to trap SIGPIPE
.
$record = $obj->recv($maxlen, $flags, $whence); $record = $obj->recv($maxlen, $flags); $record = $obj->recv($maxlen); $record = $obj->recv;
This method calls the recv()
builtin, and returns a buffer (if
one is received) or undef
on eof or error. If an eof on a stream socket is seen, $!
will be 0 on return. If the
$whence
argument is supplied, it will be filled in with the sending socket address
if possible. If the $flags
argument is not supplied, it defaults to 0. If the $maxlen
argument is not supplied, it is defaulted to the receive buffer size of the
associated filehandle (if known), or the preferred blocksize of the
associated filehandle (if known, which it usually won't be), or 8192.
$from = $obj->RECV($buffer, $maxlen, $flags); $from = $obj->RECV($buffer, $maxlen); $from = $obj->RECV($buffer);
This method calls the recv()
method with the arguments and
return rearranged to match the recv()
builtin. This is for
(eventual) support of tied filehandles.
<$filehandle>
that doesn't let stdio confuse the get/recv method.
$ok = $obj->isopen;
Returns true if the object currently has a socket attached to its
associated filehandle, and false otherwise. If this method has not been
overridden by a derived class, the value is the saved return value of the
call to the socket()
builtin (if it was called).
$ok = $obj->isconnected;
Returns true if the object's connect method has been used successfully to establish a ``session'', and that
session is still connected. If this method has not been overridden by a
derived class, the value is the saved return value of the call to the
connect()
builtin (if it was called).
$ok = $obj->isbound;
Returns true if the object's bind method has been used successfully, and the binding is still in effect. If
this method has not been overridden by a derived class, the value is the
saved return value of the call to the bind()
builtin (if it
was called).
$ok = $obj->didlisten;
Returns true if the object's listen method has been used successfully, and the object is still bound. If this
method has not been overridden by a derived class, the value is undef
on failure and the $maxqueue value used for the listen()
builtin on success.
$newobj = $obj->accept;
Returns a new object in the same class as the given object if an
accept()
call succeeds, and undef
otherwise. If the accept()
call succeeds, the new object is
marked as being open, connected, and bound.
@optvals = $obj->getsopt($level, $option); @optvals = $obj->getsopt($optname);
Returns the unpacked values from a call to the getsockopt()
builtin. In order to do the unpacking, the socket option must have been
registered with the object. See the discussion below in socket options.
Since registered socket options are known by name as well as by their level
and option values, it is possible to make calls using only option name. If
the name is not registered with the object, the return value is the same as
that for getsopt $obj -1,-1
, which is an empty return array and $! set appropriately (should be EINVAL
).
Examples:
($sotype) = $obj->getsopt('SO_TYPE'); @malinger = $obj->getsopt(SOL_SOCKET, SO_LINGER); ($sodebug) = $obj->getsopt('SOL_SOCKET', 'SO_DEBUG');
$optsetting = $obj->getropt($level, $option); $optsetting = $obj->getropt($optname);
Returns the raw value from a call to the getsockopt()
builtin.
If both the $level
and $option
arguments are given as numbers, the getsockopt()
call will be
made even if the given socket option is not registered with the object.
Otherwise, the return value for unregistered objects will be undef with the
value of $! set as described above for the getsopt method.
$ok = $obj->setsopt($level, $option, @optvalues); $ok = $obj->setsopt($optname, @optvalues);
Returns the result from a call to the setsockopt()
builtin. In
order to be able to pack the @optvalues
, the option must be registered with the object, just as for the getsopt method, above.
$ok = $obj->setropt($level, $option, $rawvalue); $ok = $obj->setropt($optname, $rawvalue);
Returns the result from a call to the setsockopt()
builtin. If
the $level
and $option
arguments are both given
as numbers, the setsockopt()
call will be made even if the
option is not registered with the object. Otherwise, unregistered options
will fail as for the setsopt method, above.
$vecstring = $obj->fhvec;
Returns a vector suitable as an argument to the 4-argument
select()
call. This is for use in doing selects with multiple
I/O streams.
($nfound, $timeleft, $rbool, $wbool, $xbool) = $obj->select($doread, $dowrite, $doxcept, $timeout); $nfound = $obj->select($doread, $dowrite, $doxcept, $timeout);
Issues a 4-argument select()
call for the associated I/O
stream. All arguments are optional. The $timeout
argument is
the same as the fourth argument to select().
The first three
are booleans, used to determine whether the select()
should
include the object's I/O stream in the corresponding parameter to the
select()
call. The return in list context is the standard two
values from select(),
follwed by booleans indicating whether
the actual select()
call found reading, writing, or exception
to be true. In scalar context, returns only the count of the number of
matching conditions. This is probably only useful when you're checking just
one of the three possible conditions.
$rval = $obj->ioctl($func, $value);
Returns the result of an ioctl()
call on the associated I/O
stream.
$rval = $obj->fcntl($func, $value);
Returns the result of an fcntl()
call on the associated I/O
stream.
$string = $obj->format_addr($sockaddr); $string = format_addr Module $sockaddr;
Returns a formatted representation of the address. This is a method so that it can be overridden by derived classes. It is used to implement ``pretty-printing'' methods for source and destination addresses.
$string = $obj->format_local_addr;
Returns a formatted representation of the local socket address associated with the object.
$string = $obj->format_remote_addr;
Returns a formatted representation of the remote socket address associated with the object.
$classname->initsockopts($level, \%optiondesc);
Given a prototype optiondesc hash ref, updates it to include all the data needed for the values it can find, and deletes the ones it can't. For example, here's a single entry from such a prototype optiondesc:
'SO_LINGER' => ['II'],
Given that, and the $level
of SOL_SOCKET
, and the incoming class name of Net::Gen
, initsockopts will attempt to evaluate SO_LINGER
in package Net::Gen
, and if it succeeds it will fill out the rest of the information in the
associated array ref, and add another key to the hash ref for the value of
SO_LINGER
(which is 128 on my system). If it can't evaluate that psuedo-constant, it
will simply delete that entry from the referenced hash. Assuming a
successful evaluation of this entry, the resulting entries would look like
this:
'SO_LINGER' => ['II', SO_LINGER+0, SOL_SOCKET+0, 2], SO_LINGER+0 => ['II', SO_LINGER+0, SOL_SOCKET+0, 2],
(All right, so the expressions would be known values, but maybe you get the idea.)
A completed optiondesc hash is a set of key-value pairs where the value is an array ref with the following elements:
[pack template, option value, option level, pack array len]
Such a completed optiondesc is one of the required arguments to the registerOptions method (see below).
$obj->registerOptions($levelname, $level, \%optiondesc);
This method attaches the socket options specified by the given option descriptions hash ref and the given level (as text and as a number) to the object. The registered set of socket options is in fact a hashref of hashrefs, where the keys are the level names and level numbers, and the values are the optiondesc hash refs which get registered.
Example:
$self->registerOptions('SOL_SOCKET', SOL_SOCKET+0, \%sockopts);
$obj->registerParamKeys(\@keynames);
This method registers the referenced keynames as valid parameters for setparams and the like for this object. The new methods can store arbitrary parameter values, but the init method will later ensure that all those keys eventually got registered. This out-of-order setup is allowed because of possible cross-dependencies between the various parameters, so they have to be set before they can be validated (in some cases).
$obj->registerParamHandlers(\@keynames, \@keyhandlers); $obj->registerParamHandlers(\%key_handler_pairs);
This method registers the referenced keynames (if they haven't already been
registered), and establishes the referenced keyhandlers as validation
routines for those keynames. Each element of the keyhandlers array must be
a code reference. When the setparams method invokes the handler, it will be called with three arguments: the
target object, the keyname in question, and the proposed new value (which
may be undef
, especially if being called from the delparams method). See the other discussion of validation routines in the setparams method description, above.
$wasiteof = $obj->ckeof;
After a 0-length read in the get()
routine, it calls this
method to determine whether such a 0-length read meant EOF. The default
method supplied here checks for non-blocking sockets (if necessary), and
for a SOCK_STREAM
socket. If EOF_NONBLOCK is true, or if the
VAL_O_NONBLOCK flag was not set in the fcntl()
flags for the socket, or if
the error code was not VAL_EAGAIN, and the socket is of type SOCK_STREAM
, then this method returns true. It returns a false value otherwise. This
method is overridable for classes like Net::Dnet
, which support SOCK_SEQPACKET
and need to make a protocol-family-specific check to tell a 0-length packet
from EOF.
$fnum = $obj->fileno;
I've strongly resisted giving people direct access to the filehandle
embedded in the object because of the problems of mixing stdio
input calls and traditional socket-level I/O. However, if you're sure you
can keep things straight, here are the rules under which it's safe to use
the embedded filehandle:
stdio
calls. Stick to sysread()
and recv().
close(),
shutdown(),
connect(),
bind(),
or listen()
built-ins. Use the
corresponding methods instead, or all bets are off.
$fh = $obj->getfh;
That $fh
is a glob ref, by the way, but that doesn't matter for calling the built-in
I/O primitives.
Net::Gen
module itself:
SO_ACCEPTCONN
,
SO_BROADCAST
,
SO_DEBUG
,
SO_DONTROUTE
,
SO_ERROR
,
SO_KEEPALIVE
,
SO_OOBINLINE
,
SO_REUSEADDR
,
SO_USELOOPBACK
,
SO_RCVBUF
,
SO_SNDBUF
,
SO_RCVTIMEO
,
SO_SNDTIMEO
,
SO_RCVLOWAT
,
SO_SNDLOWAT
,
SO_TYPE
,
SO_LINGER
Net::Gen
module itself:
SOCK_STREAM
, SOCK_DGRAM
, etc.)
socket()
call (often defaulted to
0)
getpeername(),
or an ephemeral proposed
connect()
address
connect()
getsockname(),
or an ephemeral proposed
bind()
address
bind()
listen().
This will be used if the $maxqueue argument to listen()
is
not supplied.
$connect_address = pack_sockaddr($family, $fam_addr);
Returns a packed struct sockaddr
corresponding to the provided $family
(which must be a number)
and the address-family-specific $fam_addr
(pre-packed).
($family, $fam_addr) = unpack_sockaddr($packed_address);
The inverse of pack_sockaddr().
Config
module is a string representing the value found ($Config::Config{'o_nonblock'}
), whereas the value from
VAL_O_NONBLOCK is an integer, suitable for passing to sysopen()
or for
eventual use in fcntl().
Config
module ($Config::Config{'eagain'}
) in that the latter is a string, typically "EAGAIN"
.
read()
system call on a non-blocking socket which
has no data available. This is similar to the string representation of the
value available from the Config
module as
$Config::Config{'rd_nodata'}
.
Config
module as
$Config::Config{'d_eofnblk'}
), except that EOF_NONBLOCK is always defined.
$CommentsMailTo = "perl5@dcs.ed.ac.uk"; include("../syssies_footer.inc");?>