5 our($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
10 Socket, sockaddr_in, sockaddr_un, inet_aton, inet_ntoa, inet_pton, inet_ntop - load the C socket.h defines and structure manipulators
16 $proto = getprotobyname('udp');
17 socket(Socket_Handle, PF_INET, SOCK_DGRAM, $proto);
18 $iaddr = gethostbyname('hishost.com');
19 $port = getservbyname('time', 'udp');
20 $sin = sockaddr_in($port, $iaddr);
21 send(Socket_Handle, 0, 0, $sin);
23 $proto = getprotobyname('tcp');
24 socket(Socket_Handle, PF_INET, SOCK_STREAM, $proto);
25 $port = getservbyname('smtp', 'tcp');
26 $sin = sockaddr_in($port,inet_aton("127.1"));
27 $sin = sockaddr_in(7,inet_aton("localhost"));
28 $sin = sockaddr_in(7,INADDR_LOOPBACK);
29 connect(Socket_Handle,$sin);
31 ($port, $iaddr) = sockaddr_in(getpeername(Socket_Handle));
32 $peer_host = gethostbyaddr($iaddr, AF_INET);
33 $peer_addr = inet_ntoa($iaddr);
35 $proto = getprotobyname('tcp');
36 socket(Socket_Handle, PF_UNIX, SOCK_STREAM, $proto);
37 unlink('/var/run/usock');
38 $sun = sockaddr_un('/var/run/usock');
39 connect(Socket_Handle,$sun);
43 This module is just a translation of the C F<socket.h> file.
44 Unlike the old mechanism of requiring a translated F<socket.ph>
45 file, this uses the B<h2xs> program (see the Perl source distribution)
46 and your native C compiler. This means that it has a
47 far more likely chance of getting the numbers right. This includes
48 all of the commonly used pound-defines like AF_INET, SOCK_STREAM, etc.
50 Also, some common socket "newline" constants are provided: the
51 constants C<CR>, C<LF>, and C<CRLF>, as well as C<$CR>, C<$LF>, and
52 C<$CRLF>, which map to C<\015>, C<\012>, and C<\015\012>. If you do
53 not want to use the literal characters in your programs, then use
54 the constants provided here. They are not exported by default, but can
55 be imported individually, and with the C<:crlf> export tag:
57 use Socket qw(:DEFAULT :crlf);
59 In addition, some structure manipulation functions are available:
63 =item inet_aton HOSTNAME
65 Takes a string giving the name of a host, and translates that to an
66 opaque string (if programming in C, struct in_addr). Takes arguments
67 of both the 'rtfm.mit.edu' type and '18.181.0.24'. If the host name
68 cannot be resolved, returns undef. For multi-homed hosts (hosts with
69 more than one address), the first address found is returned.
71 For portability do not assume that the result of inet_aton() is 32
72 bits wide, in other words, that it would contain only the IPv4 address
75 =item inet_ntoa IP_ADDRESS
77 Takes a string (an opaque string as returned by inet_aton(),
78 or a v-string representing the four octets of the IPv4 address in
79 network order) and translates it into a string of the form 'd.d.d.d'
80 where the 'd's are numbers less than 256 (the normal human-readable
81 four dotted number notation for Internet addresses).
85 Note: does not return a number, but a packed string.
87 Returns the 4-byte wildcard ip address which specifies any
88 of the hosts ip addresses. (A particular machine can have
89 more than one ip address, each address corresponding to
90 a particular network interface. This wildcard address
91 allows you to bind to all of them simultaneously.)
92 Normally equivalent to inet_aton('0.0.0.0').
94 =item INADDR_BROADCAST
96 Note: does not return a number, but a packed string.
98 Returns the 4-byte 'this-lan' ip broadcast address.
99 This can be useful for some protocols to solicit information
100 from all servers on the same LAN cable.
101 Normally equivalent to inet_aton('255.255.255.255').
103 =item INADDR_LOOPBACK
105 Note - does not return a number.
107 Returns the 4-byte loopback address. Normally equivalent
108 to inet_aton('localhost').
112 Note - does not return a number.
114 Returns the 4-byte 'invalid' ip address. Normally equivalent
115 to inet_aton('255.255.255.255').
119 Returns the 16-byte wildcard IPv6 address. Normally equivalent
120 to inet_pton(AF_INET6, "::")
122 =item IN6ADDR_LOOPBACK
124 Returns the 16-byte loopback IPv6 address. Normally equivalent
125 to inet_pton(AF_INET6, "::1")
127 =item sockaddr_family SOCKADDR
129 Takes a sockaddr structure (as returned by pack_sockaddr_in(),
130 pack_sockaddr_un() or the perl builtin functions getsockname() and
131 getpeername()) and returns the address family tag. It will match the
132 constant AF_INET for a sockaddr_in and AF_UNIX for a sockaddr_un. It
133 can be used to figure out what unpacker to use for a sockaddr of
136 =item sockaddr_in PORT, ADDRESS
138 =item sockaddr_in SOCKADDR_IN
140 In a list context, unpacks its SOCKADDR_IN argument and returns an array
141 consisting of (PORT, ADDRESS). In a scalar context, packs its (PORT,
142 ADDRESS) arguments as a SOCKADDR_IN and returns it. If this is confusing,
143 use pack_sockaddr_in() and unpack_sockaddr_in() explicitly.
145 =item pack_sockaddr_in PORT, IP_ADDRESS
147 Takes two arguments, a port number and an opaque string, IP_ADDRESS
148 (as returned by inet_aton(), or a v-string). Returns the sockaddr_in
149 structure with those arguments packed in with AF_INET filled in. For
150 Internet domain sockets, this structure is normally what you need for
151 the arguments in bind(), connect(), and send(), and is also returned
152 by getpeername(), getsockname() and recv().
154 =item unpack_sockaddr_in SOCKADDR_IN
156 Takes a sockaddr_in structure (as returned by pack_sockaddr_in()) and
157 returns an array of two elements: the port and an opaque string
158 representing the IP address (you can use inet_ntoa() to convert the
159 address to the four-dotted numeric format). Will croak if the
160 structure does not have AF_INET in the right place.
162 =item sockaddr_in6 PORT, IP6_ADDRESS, [ SCOPE_ID, [ FLOWINFO ] ]
164 =item sockaddr_in6 SOCKADDR_IN6
166 In list context, unpacks its SOCKADDR_IN6 argument according to
167 unpack_sockaddr_in6(). In scalar context, packs its arguments according to
170 =item pack_sockaddr_in6 PORT, IP6_ADDRESS, [ SCOPE_ID, [ FLOWINFO ] ]
172 Takes two to four arguments, a port number, an opaque string (as returned by
173 inet_pton()), optionally a scope ID number, and optionally a flow label
174 number. Returns the sockaddr_in6 structure with those arguments packed in
175 with AF_INET6 filled in. IPv6 equivalent of pack_sockaddr_in().
177 =item unpack_sockaddr_in6 SOCKADDR_IN6
179 Takes a sockaddr_in6 structure (as returned by pack_sockaddr_in6()) and
180 returns an array of four elements: the port number, an opaque string
181 representing the IPv6 address, the scope ID, and the flow label. (You can
182 use inet_ntop() to convert the address to the usual string format). Will
183 croak if the structure does not have AF_INET6 in the right place.
185 =item sockaddr_un PATHNAME
187 =item sockaddr_un SOCKADDR_UN
189 In a list context, unpacks its SOCKADDR_UN argument and returns an array
190 consisting of (PATHNAME). In a scalar context, packs its PATHNAME
191 arguments as a SOCKADDR_UN and returns it. If this is confusing, use
192 pack_sockaddr_un() and unpack_sockaddr_un() explicitly.
193 These are only supported if your system has E<lt>F<sys/un.h>E<gt>.
195 =item pack_sockaddr_un PATH
197 Takes one argument, a pathname. Returns the sockaddr_un structure with
198 that path packed in with AF_UNIX filled in. For unix domain sockets, this
199 structure is normally what you need for the arguments in bind(),
200 connect(), and send(), and is also returned by getpeername(),
201 getsockname() and recv().
203 =item unpack_sockaddr_un SOCKADDR_UN
205 Takes a sockaddr_un structure (as returned by pack_sockaddr_un())
206 and returns the pathname. Will croak if the structure does not
207 have AF_UNIX in the right place.
209 =item inet_pton ADDRESS_FAMILY, HOSTNAME
211 Takes an address family, either AF_INET or AF_INET6, and a string giving
212 the name of a host, and translates that to an opaque string
213 (if programming in C, struct in_addr or struct in6_addr depending on the
214 address family passed in). The host string may be a string hostname, such
215 as 'www.perl.org', or an IP address. If using an IP address, the type of
216 IP address must be consistent with the address family passed into the function.
218 This function is not exported by default.
220 =item inet_ntop ADDRESS_FAMILY, IP_ADDRESS
222 Takes an address family, either AF_INET or AF_INET6, and a string
223 (an opaque string as returned by inet_aton() or inet_pton()) and
224 translates it to an IPv4 or IPv6 address string.
226 This function is not exported by default.
228 =item getaddrinfo HOST, SERVICE, [ HINTS ]
230 Given at least one of a hostname and a service name, returns a list of address
231 structures to listen on or connect to. HOST and SERVICE should be plain
232 strings (or a numerical port number for SERVICE). If present, HINTS should be
233 a reference to a HASH, where the following keys are recognised:
239 A bitfield containing C<AI_*> constants
243 Restrict to only generating addresses in this address family
245 =item socktype => INT
247 Restrict to only generating addresses of this socket type
249 =item protocol => INT
251 Restrict to only generating addresses for this protocol
255 The return value will be a list; the first value being an error indication,
256 followed by a list of address structures (if no error occured).
258 my ( $err, @results ) = getaddrinfo( ... );
260 The error value will be a dualvar; comparable to the C<EI_*> error constants,
261 or printable as a human-readable error message string. Each value in the
262 results list will be a HASH reference containing the following fields:
268 The address family (e.g. AF_INET)
270 =item socktype => INT
272 The socket type (e.g. SOCK_STREAM)
274 =item protocol => INT
276 The protocol (e.g. IPPROTO_TCP)
280 The address in a packed string (such as would be returned by pack_sockaddr_in)
282 =item canonname => STRING
284 The canonical name for the host if the C<AI_CANONNAME> flag was provided, or
285 C<undef> otherwise. This field will only be present on the first returned
290 =item getnameinfo ADDR, FLAGS
292 Given a packed socket address (such as from C<getsockname>, C<getpeername>, or
293 returned by C<getaddrinfo> in a C<addr> field), returns the hostname and
294 symbolic service name it represents. FLAGS may be a bitmask of C<NI_*>
295 constants, or defaults to 0 if unspecified.
297 The return value will be a list; the first value being an error condition,
298 followed by the hostname and service name.
300 my ( $err, $host, $service ) = getnameinfo( ... );
302 The error value will be a dualvar; comparable to the C<EI_*> error constants,
303 or printable as a human-readable error message string. The host and service
304 names will be plain strings.
310 =item pack_ipv6_mreq IP6_MULTIADDR, INTERFACE
312 Takes an IPv6 address and an interface number. Returns the ipv6_mreq structure
313 with those arguments packed in. Suitable for use with the
314 C<IPV6_ADD_MEMBERSHIP> and C<IPV6_DROP_MEMBERSHIP> sockopts.
316 =item unpack_ipv6_mreq IPV6_MREQ
318 Takes an ipv6_mreq structure and returns a list of two elements; the IPv6
319 address and an interface number.
326 use warnings::register;
332 # <@Nicholas> you can't change @EXPORT without breaking the implicit API
333 # Please put any new constants in @EXPORT_OK!
337 pack_sockaddr_in unpack_sockaddr_in
338 pack_sockaddr_un unpack_sockaddr_un
339 pack_sockaddr_in6 unpack_sockaddr_in6
340 sockaddr_in sockaddr_in6 sockaddr_un
341 INADDR_ANY INADDR_BROADCAST INADDR_LOOPBACK INADDR_NONE
482 SO_SECURITY_AUTHENTICATION
483 SO_SECURITY_ENCRYPTION_NETWORK
484 SO_SECURITY_ENCRYPTION_TRANSPORT
496 @EXPORT_OK = qw(CR LF CRLF $CR $LF $CRLF
507 IN6ADDR_ANY IN6ADDR_LOOPBACK
565 crlf => [qw(CR LF CRLF $CR $LF $CRLF)],
566 all => [@EXPORT, @EXPORT_OK],
572 sub CRLF () {"\015\012"}
580 if (@_ == 6 && !wantarray) { # perl5.001m compat; use this && die
581 my($af, $port, @quad) = @_;
582 warnings::warn "6-ARG sockaddr_in call is deprecated"
583 if warnings::enabled();
584 pack_sockaddr_in($port, inet_aton(join('.', @quad)));
585 } elsif (wantarray) {
586 croak "usage: (port,iaddr) = sockaddr_in(sin_sv)" unless @_ == 1;
587 unpack_sockaddr_in(@_);
589 croak "usage: sin_sv = sockaddr_in(port,iaddr))" unless @_ == 2;
590 pack_sockaddr_in(@_);
596 croak "usage: (port,in6addr,scope_id,flowinfo) = sockaddr_in6(sin6_sv)" unless @_ == 1;
597 unpack_sockaddr_in6(@_);
600 croak "usage: sin6_sv = sockaddr_in6(port,in6addr,[scope_id,[flowinfo]])" unless @_ >= 2 and @_ <= 4;
601 pack_sockaddr_in6(@_);
607 croak "usage: (filename) = sockaddr_un(sun_sv)" unless @_ == 1;
608 unpack_sockaddr_un(@_);
610 croak "usage: sun_sv = sockaddr_un(filename)" unless @_ == 1;
611 pack_sockaddr_un(@_);
619 if( defined &getaddrinfo ) {
620 # These are not part of the API, nothing uses them, and deleting them
621 # reduces the size of %Socket:: by about 12K
622 delete $Socket::{fake_getaddrinfo};
623 delete $Socket::{fake_getnameinfo};
625 require Scalar::Util;
627 *getaddrinfo = \&fake_getaddrinfo;
628 *getnameinfo = \&fake_getnameinfo;
630 # These numbers borrowed from GNU libc's implementation, but since
631 # they're only used by our emulation, it doesn't matter if the real
632 # platform's values differ
637 # RFC 2553 doesn't define this but Linux does - lets be nice and
638 # provide it since we can
639 AI_NUMERICSERV => 1024,
653 foreach my $name ( keys %constants ) {
654 my $value = $constants{$name};
657 defined &$name or *$name = sub () { $value };
661 # These strings from RFC 2553
662 EAI_BADFLAGS() => "invalid value for ai_flags",
663 EAI_NONAME() => "nodename nor servname provided, or not known",
664 EAI_NODATA() => "no address associated with nodename",
665 EAI_FAMILY() => "ai_family not supported",
666 EAI_SERVICE() => "servname not supported for ai_socktype",
670 # The following functions are used if the system does not have a
671 # getaddrinfo(3) function in libc; and are used to emulate it for the AF_INET
674 # Borrowed from Regexp::Common::net
675 my $REGEXP_IPv4_DECIMAL = qr/25[0-5]|2[0-4][0-9]|1?[0-9][0-9]{1,2}/;
676 my $REGEXP_IPv4_DOTTEDQUAD = qr/$REGEXP_IPv4_DECIMAL\.$REGEXP_IPv4_DECIMAL\.$REGEXP_IPv4_DECIMAL\.$REGEXP_IPv4_DECIMAL/;
681 my $errstr = $errno == 0 ? "" : ( $errstr{$errno} || $errno );
682 return Scalar::Util::dualvar( $errno, $errstr );
687 my ( $node, $service, $hints ) = @_;
689 $node = "" unless defined $node;
691 $service = "" unless defined $service;
693 my ( $family, $socktype, $protocol, $flags ) = @$hints{qw( family socktype protocol flags )};
695 $family ||= Socket::AF_INET(); # 0 == AF_UNSPEC, which we want too
696 $family == Socket::AF_INET() or return fake_makeerr( EAI_FAMILY() );
704 my $flag_passive = $flags & AI_PASSIVE(); $flags &= ~AI_PASSIVE();
705 my $flag_canonname = $flags & AI_CANONNAME(); $flags &= ~AI_CANONNAME();
706 my $flag_numerichost = $flags & AI_NUMERICHOST(); $flags &= ~AI_NUMERICHOST();
707 my $flag_numericserv = $flags & AI_NUMERICSERV(); $flags &= ~AI_NUMERICSERV();
709 $flags == 0 or return fake_makeerr( EAI_BADFLAGS() );
711 $node eq "" and $service eq "" and return fake_makeerr( EAI_NONAME() );
716 return fake_makeerr( EAI_NONAME() ) if( $flag_numerichost and $node !~ m/^$REGEXP_IPv4_DOTTEDQUAD$/ );
717 ( $canonname, undef, undef, undef, @addrs ) = gethostbyname( $node );
718 defined $canonname or return fake_makeerr( EAI_NONAME() );
720 undef $canonname unless $flag_canonname;
723 $addrs[0] = $flag_passive ? Socket::inet_aton( "0.0.0.0" )
724 : Socket::inet_aton( "127.0.0.1" );
727 my @ports; # Actually ARRAYrefs of [ socktype, protocol, port ]
730 $protname = getprotobynumber( $protocol );
733 if( $service ne "" and $service !~ m/^\d+$/ ) {
734 return fake_makeerr( EAI_NONAME() ) if( $flag_numericserv );
735 getservbyname( $service, $protname ) or return fake_makeerr( EAI_SERVICE() );
738 foreach my $this_socktype ( Socket::SOCK_STREAM(), Socket::SOCK_DGRAM(), Socket::SOCK_RAW() ) {
739 next if $socktype and $this_socktype != $socktype;
741 my $this_protname = "raw";
742 $this_socktype == Socket::SOCK_STREAM() and $this_protname = "tcp";
743 $this_socktype == Socket::SOCK_DGRAM() and $this_protname = "udp";
745 next if $protname and $this_protname ne $protname;
748 if( $service ne "" ) {
749 if( $service =~ m/^\d+$/ ) {
753 ( undef, undef, $port, $this_protname ) = getservbyname( $service, $this_protname );
754 next unless defined $port;
761 push @ports, [ $this_socktype, scalar getprotobyname( $this_protname ) || 0, $port ];
765 foreach my $addr ( @addrs ) {
766 foreach my $portspec ( @ports ) {
767 my ( $socktype, $protocol, $port ) = @$portspec;
770 socktype => $socktype,
771 protocol => $protocol,
772 addr => Socket::pack_sockaddr_in( $port, $addr ),
778 # Only supply canonname for the first result
779 if( defined $canonname ) {
780 $ret[0]->{canonname} = $canonname;
783 return ( fake_makeerr( 0 ), @ret );
788 my ( $addr, $flags ) = @_;
790 my ( $port, $inetaddr );
791 eval { ( $port, $inetaddr ) = Socket::unpack_sockaddr_in( $addr ) }
792 or return fake_makeerr( EAI_FAMILY() );
794 my $family = Socket::AF_INET();
798 my $flag_numerichost = $flags & NI_NUMERICHOST(); $flags &= ~NI_NUMERICHOST();
799 my $flag_numericserv = $flags & NI_NUMERICSERV(); $flags &= ~NI_NUMERICSERV();
800 my $flag_namereqd = $flags & NI_NAMEREQD(); $flags &= ~NI_NAMEREQD();
801 my $flag_dgram = $flags & NI_DGRAM() ; $flags &= ~NI_DGRAM();
803 $flags == 0 or return fake_makeerr( EAI_BADFLAGS() );
806 if( $flag_numerichost ) {
807 $node = Socket::inet_ntoa( $inetaddr );
810 $node = gethostbyaddr( $inetaddr, $family );
811 if( !defined $node ) {
812 return fake_makeerr( EAI_NONAME() ) if $flag_namereqd;
813 $node = Socket::inet_ntoa( $inetaddr );
818 if( $flag_numericserv ) {
822 my $protname = $flag_dgram ? "udp" : "";
823 $service = getservbyport( $port, $protname );
824 if( !defined $service ) {
829 return ( fake_makeerr( 0 ), $node, $service );