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
289 =item getnameinfo ADDR, FLAGS
291 Given a packed socket address (such as from C<getsockname>, C<getpeername>, or
292 returned by C<getaddrinfo> in a C<addr> field), returns the hostname and
293 symbolic service name it represents. FLAGS may be a bitmask of C<NI_*>
294 constants, or defaults to 0 if unspecified.
296 The return value will be a list; the first value being an error condition,
297 followed by the hostname and service name.
299 my ( $err, $host, $service ) = getnameinfo( ... );
301 The error value will be a dualvar; comparable to the C<EI_*> error constants,
302 or printable as a human-readable error message string. The host and service
303 names will be plain strings.
310 use warnings::register;
316 # <@Nicholas> you can't change @EXPORT without breaking the implicit API
317 # Please put any new constants in @EXPORT_OK!
321 pack_sockaddr_in unpack_sockaddr_in
322 pack_sockaddr_un unpack_sockaddr_un
323 pack_sockaddr_in6 unpack_sockaddr_in6
324 sockaddr_in sockaddr_in6 sockaddr_un
325 INADDR_ANY INADDR_BROADCAST INADDR_LOOPBACK INADDR_NONE
466 SO_SECURITY_AUTHENTICATION
467 SO_SECURITY_ENCRYPTION_NETWORK
468 SO_SECURITY_ENCRYPTION_TRANSPORT
480 @EXPORT_OK = qw(CR LF CRLF $CR $LF $CRLF
488 IN6ADDR_ANY IN6ADDR_LOOPBACK
536 crlf => [qw(CR LF CRLF $CR $LF $CRLF)],
537 all => [@EXPORT, @EXPORT_OK],
543 sub CRLF () {"\015\012"}
551 if (@_ == 6 && !wantarray) { # perl5.001m compat; use this && die
552 my($af, $port, @quad) = @_;
553 warnings::warn "6-ARG sockaddr_in call is deprecated"
554 if warnings::enabled();
555 pack_sockaddr_in($port, inet_aton(join('.', @quad)));
556 } elsif (wantarray) {
557 croak "usage: (port,iaddr) = sockaddr_in(sin_sv)" unless @_ == 1;
558 unpack_sockaddr_in(@_);
560 croak "usage: sin_sv = sockaddr_in(port,iaddr))" unless @_ == 2;
561 pack_sockaddr_in(@_);
567 croak "usage: (port,in6addr,scope_id,flowinfo) = sockaddr_in6(sin6_sv)" unless @_ == 1;
568 unpack_sockaddr_in6(@_);
571 croak "usage: sin6_sv = sockaddr_in6(port,in6addr,[scope_id,[flowinfo]])" unless @_ >= 2 and @_ <= 4;
572 pack_sockaddr_in6(@_);
578 croak "usage: (filename) = sockaddr_un(sun_sv)" unless @_ == 1;
579 unpack_sockaddr_un(@_);
581 croak "usage: sun_sv = sockaddr_un(filename)" unless @_ == 1;
582 pack_sockaddr_un(@_);
590 if( !defined &getaddrinfo ) {
591 require Scalar::Util;
593 *getaddrinfo = \&fake_getaddrinfo;
594 *getnameinfo = \&fake_getnameinfo;
596 # These numbers borrowed from GNU libc's implementation, but since
597 # they're only used by our emulation, it doesn't matter if the real
598 # platform's values differ
603 # RFC 2553 doesn't define this but Linux does - lets be nice and
604 # provide it since we can
605 AI_NUMERICSERV => 1024,
619 foreach my $name ( keys %constants ) {
620 my $value = $constants{$name};
623 defined &$name or *$name = sub () { $value };
627 # These strings from RFC 2553
628 EAI_BADFLAGS() => "invalid value for ai_flags",
629 EAI_NONAME() => "nodename nor servname provided, or not known",
630 EAI_NODATA() => "no address associated with nodename",
631 EAI_FAMILY() => "ai_family not supported",
632 EAI_SERVICE() => "servname not supported for ai_socktype",
636 # The following functions are used if the system does not have a
637 # getaddrinfo(3) function in libc; and are used to emulate it for the AF_INET
640 # Borrowed from Regexp::Common::net
641 my $REGEXP_IPv4_DECIMAL = qr/25[0-5]|2[0-4][0-9]|1?[0-9][0-9]{1,2}/;
642 my $REGEXP_IPv4_DOTTEDQUAD = qr/$REGEXP_IPv4_DECIMAL\.$REGEXP_IPv4_DECIMAL\.$REGEXP_IPv4_DECIMAL\.$REGEXP_IPv4_DECIMAL/;
647 my $errstr = $errno == 0 ? "" : ( $errstr{$errno} || $errno );
648 return Scalar::Util::dualvar( $errno, $errstr );
653 my ( $node, $service, $hints ) = @_;
655 $node = "" unless defined $node;
657 $service = "" unless defined $service;
659 my ( $family, $socktype, $protocol, $flags ) = @$hints{qw( family socktype protocol flags )};
661 $family ||= Socket::AF_INET(); # 0 == AF_UNSPEC, which we want too
662 $family == Socket::AF_INET() or return fake_makeerr( EAI_FAMILY() );
670 my $flag_passive = $flags & AI_PASSIVE(); $flags &= ~AI_PASSIVE();
671 my $flag_canonname = $flags & AI_CANONNAME(); $flags &= ~AI_CANONNAME();
672 my $flag_numerichost = $flags & AI_NUMERICHOST(); $flags &= ~AI_NUMERICHOST();
673 my $flag_numericserv = $flags & AI_NUMERICSERV(); $flags &= ~AI_NUMERICSERV();
675 $flags == 0 or return fake_makeerr( EAI_BADFLAGS() );
677 $node eq "" and $service eq "" and return fake_makeerr( EAI_NONAME() );
682 return fake_makeerr( EAI_NONAME() ) if( $flag_numerichost and $node !~ m/^$REGEXP_IPv4_DOTTEDQUAD$/ );
683 ( $canonname, undef, undef, undef, @addrs ) = gethostbyname( $node );
684 defined $canonname or return fake_makeerr( EAI_NONAME() );
686 undef $canonname unless $flag_canonname;
689 $addrs[0] = $flag_passive ? Socket::inet_aton( "0.0.0.0" )
690 : Socket::inet_aton( "127.0.0.1" );
693 my @ports; # Actually ARRAYrefs of [ socktype, protocol, port ]
696 $protname = getprotobynumber( $protocol );
699 if( $service ne "" and $service !~ m/^\d+$/ ) {
700 return fake_makeerr( EAI_NONAME() ) if( $flag_numericserv );
701 getservbyname( $service, $protname ) or return fake_makeerr( EAI_SERVICE() );
704 foreach my $this_socktype ( Socket::SOCK_STREAM(), Socket::SOCK_DGRAM(), Socket::SOCK_RAW() ) {
705 next if $socktype and $this_socktype != $socktype;
707 my $this_protname = "raw";
708 $this_socktype == Socket::SOCK_STREAM() and $this_protname = "tcp";
709 $this_socktype == Socket::SOCK_DGRAM() and $this_protname = "udp";
711 next if $protname and $this_protname ne $protname;
714 if( $service ne "" ) {
715 if( $service =~ m/^\d+$/ ) {
719 ( undef, undef, $port, $this_protname ) = getservbyname( $service, $this_protname );
720 next unless defined $port;
727 push @ports, [ $this_socktype, scalar getprotobyname( $this_protname ) || 0, $port ];
731 foreach my $addr ( @addrs ) {
732 foreach my $portspec ( @ports ) {
733 my ( $socktype, $protocol, $port ) = @$portspec;
736 socktype => $socktype,
737 protocol => $protocol,
738 addr => Socket::pack_sockaddr_in( $port, $addr ),
739 canonname => $canonname,
744 return ( fake_makeerr( 0 ), @ret );
749 my ( $addr, $flags ) = @_;
751 my ( $port, $inetaddr );
752 eval { ( $port, $inetaddr ) = Socket::unpack_sockaddr_in( $addr ) }
753 or return fake_makeerr( EAI_FAMILY() );
755 my $family = Socket::AF_INET();
759 my $flag_numerichost = $flags & NI_NUMERICHOST(); $flags &= ~NI_NUMERICHOST();
760 my $flag_numericserv = $flags & NI_NUMERICSERV(); $flags &= ~NI_NUMERICSERV();
761 my $flag_namereqd = $flags & NI_NAMEREQD(); $flags &= ~NI_NAMEREQD();
762 my $flag_dgram = $flags & NI_DGRAM() ; $flags &= ~NI_DGRAM();
764 $flags == 0 or return fake_makeerr( EAI_BADFLAGS() );
767 if( $flag_numerichost ) {
768 $node = Socket::inet_ntoa( $inetaddr );
771 $node = gethostbyaddr( $inetaddr, $family );
772 if( !defined $node ) {
773 return fake_makeerr( EAI_NONAME() ) if $flag_namereqd;
774 $node = Socket::inet_ntoa( $inetaddr );
779 if( $flag_numericserv ) {
783 my $protname = $flag_dgram ? "udp" : "";
784 $service = getservbyport( $port, $protname );
785 if( !defined $service ) {
790 return ( fake_makeerr( 0 ), $node, $service );