Why not adopt me?
NAME
Net::Gen - generic sockets interface handling
SYNOPSIS
use Net::Gen;
DESCRIPTION
The 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
and Net::TCP
, which are layered atop Net::Gen
.
Public Methods
- new
-
Usage:
$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.) - init
-
Usage:
return undef unless $self = $self->init;
Verifies that all previous parameter assignments are valid (via
checkparams
). Returns the incoming object on success, andundef
on failure. - checkparams
-
Usage:
$ok = $obj->checkparams;
Verifies that all previous parameter assignments are valid. (Normally called only via the
init
method, rather than directly.) - setparams
-
Usage:
$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, andundef
otherwise. - setparam
-
Usage:
$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, andundef
otherwise. - delparams
-
Usage:
$ok = $obj->delparams(\@keynames);
Removes the settings for the specified parameters. Uses the
setparams
method (withundef
for the values) to validate that the removal is allowed by the owning object. If the invocation ofsetparams
is successful, then the parameters in question are removed. Returns 1 if all the removals were successful, andundef
otherwise. - delparam
-
Usage:
$ok = $obj->delparam($keyname);
Sugar-coated call to the
delparams
method. Functions just like it. - getparams
-
Usage:
%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. - getparam
-
Usage:
$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. - open
-
Usage:
$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) arePF
,AF
,proto
, andtype
. Returns true if the socket() call results in an open filehandle,undef
otherwise. - listen
-
Usage:
$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 toSOMAXCONN
. If theSOMAXCONN
constant is not available in your configuration, the default value used for thelisten
method is 5. This method will fail if the object is not bound and cannot be made bound by a simple call to itsbind
method. - bind
-
Usage:
$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, thesrcaddrlist
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 thesrcaddrlist
parameter is not set to an array reference, if thesrcaddr
parameter is a non-null string, it will be used. Finally, if neithersrcaddrlist
norsrcaddr
is suitably set, theAF
parameter will be used to construct asockaddr
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 thegetsockinfo
method will be made, and then the value from a call to theisbound
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. - unbind
-
Usage:
$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, thesrcaddrlist
object parameter is removed (via the object'sdelparams
method). The return value from this method is indeterminate, but will almost always be the value 1. - connect
-
Usage:
$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, itsopen
method is called. If it's not open after that,undef
is returned. If it is open, and if either of itssrcaddrlist
orsrcaddr
parameters are set to indicate that a bind() is desired, and it is not currently bound, itsbind
method is called. If thebind
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 thedstaddrlist
parameter is not an array reference, a single attempt is made to call connect() with thedstaddr
object parameter. If no connect() call succeeded,undef
is returned. Finally, a call is made to the object'sgetsockinfo
method, and then the value from a call to itsisconnected
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. - getsockinfo
-
Usage:
$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, thedstaddr
parameter is set to that returned sockaddr. If both socket addresses were found, the getpeername() value is returned, otherwiseundef
is returned.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.
- shutdown
-
Usage:
$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.Returns 1 if nothing to do, otherwise propagates the return from the shutdown() builtin.
- stopio
-
Usage:
$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 thedelparams
method for the keys ofsrcaddr
anddstaddr
. - close
-
Usage:
$ok = $obj->close;
The
close
method is like a call to theshutdown
method followed by a call to thestopio
method. It is the standard way to close down an object. - send
-
Usage:
$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 trapSIGPIPE
. - sendto
-
Usage:
$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 trapSIGPIPE
. - put
-
Usage:
$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 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 trapSIGPIPE
. - recv
-
Usage:
$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 beundef
as well as the return value. 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. - get
-
This is identical to the
recv
method, except that its name is not (yet) known to perl, so indirect calls work, as well as object-style calls. - getline
-
This is a simulation of
<$filehandle>
that doesn't let stdio confuse theget
/recv
method. - isopen
-
Usage:
$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).
- isconnected
-
Usage:
$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). - isbound
-
Usage:
$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). - didlisten
-
Usage:
$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 isundef
on failure and the$maxqueue
value used for the listen() builtin on success. - getsopt
-
Usage:
@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 beEINVAL
).Examples:
($sotype) = $obj->getsopt('SO_TYPE'); @malinger = $obj->getsopt(SOL_SOCKET, SO_LINGER); ($sodebug) = $obj->getsopt('SOL_SOCKET', 'SO_DEBUG');
- getropt
-
Usage:
$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 thegetsopt
method. - setsopt
-
Usage:
$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 thegetsopt
method, above. - setropt
-
Usage:
$ok = $obj->setsopt($level, $option, $rawvalue); $ok = $obj->setsopt($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. - fhvec
-
Usage:
$vecstring = $obj->fhvec;
Returns a vector suitable as an argument to the 4-argument select() call. For use in doing selects with multiple I/O streams.
- select
-
Usage:
($nfound, $timeleft, $rbool, $wbool, $xbool) = $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 is the standard two values from select(), follwed by booleans indicating whether the actual select() call found reading, writing, or exception to be true.
- ioctl
-
Usage:
$rval = $obj->ioctl($func, $value);
Returns the result of an ioctl() call on the associated I/O stream.
- fcntl
-
Usage:
$rval = $obj->fcntl($func, $value);
Returns the result of an fcntl() call on the associated I/O stream.
- format_addr
-
Usage:
$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.
- format_local_addr
-
Usage:
$string = $obj->format_local_addr;
Returns a formatted representation of the local socket address associated with the object.
- format_remote_addr
-
Usage:
$string = $obj->format_remote_addr;
Returns a formatted representation of the remote socket address associated with the object.
Protected Methods
Yes, I know that Perl doesn't really have protected methods as such. However, these are the methods which are only useful for implementing derived classes, and not for the general user.
- initsockopts
-
Usage:
$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 ofNet::Gen
,initsockopts
will attempt to evaluateSO_LINGER
in packageNet::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 ofSO_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). - registerOptions
-
Usage:
$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);
- registerParamKeys
-
Usage:
$obj->registerParamKeys(\@keynames);
This method registers the referenced keynames as valid parameters for
setparams
and the like for this object. Thenew
methods can store arbitrary parameter values, but theinit
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). - registerParamHandlers
-
Usage:
$obj->registerParamHandlers(\@keynames, \@keyhandlers);
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 beundef
, especially if being called from thedelparams
method). See the other discussion of validation routines in thesetparams
method description, above.
Known Socket Options
These are the socket options known to the 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
Known Object Parameters
These are the object parameters registered by the Net::Gen
module itself:
- PF
-
Protocol family for this object
- AF
-
Address family (will default from PF, and vice versa)
- type
-
The socket type to create (
SOCK_STREAM
,SOCK_DGRAM
, etc.) - proto
-
The protocol to pass to the socket() call (often defaulted to 0)
- dstaddr
-
The result of getpeername(), or an ephemeral proposed connect() address
- dstaddrlist
-
A reference to an array of socket addresses to try for connect()
- srcaddr
-
The result of getsockname(), or an ephemeral proposed bind() address
- srcaddrlist
-
A reference to an array of socket addresses to try for bind()
Non-Method Subroutines
- pack_sockaddr
-
Usage:
$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). - unpack_sockaddr
-
Usage:
($family, $fam_addr) = unpack_sockaddr($packed_address);
The inverse of pack_sockaddr().
Exports
- default
-
None.
- exportable
-
pack_sockaddr
,unpack_sockaddr
-
None, since that version of Exporter.pm is not yet standard. Wait for Perl version 5.002.
AUTHOR
Spider Boardman <spider@Orb.Nashua.NH.US>