ada: Update copyright notice
[official-gcc.git] / gcc / ada / libgnat / g-socket.ads
blobd49245290ce1bbaf9c84a8ea0e2eb6e703d926e0
1 ------------------------------------------------------------------------------
2 -- --
3 -- GNAT COMPILER COMPONENTS --
4 -- --
5 -- G N A T . S O C K E T S --
6 -- --
7 -- S p e c --
8 -- --
9 -- Copyright (C) 2001-2023, AdaCore --
10 -- --
11 -- GNAT is free software; you can redistribute it and/or modify it under --
12 -- terms of the GNU General Public License as published by the Free Soft- --
13 -- ware Foundation; either version 3, or (at your option) any later ver- --
14 -- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE. --
17 -- --
18 -- As a special exception under Section 7 of GPL version 3, you are granted --
19 -- additional permissions described in the GCC Runtime Library Exception, --
20 -- version 3.1, as published by the Free Software Foundation. --
21 -- --
22 -- You should have received a copy of the GNU General Public License and --
23 -- a copy of the GCC Runtime Library Exception along with this program; --
24 -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
25 -- <http://www.gnu.org/licenses/>. --
26 -- --
27 -- GNAT was originally developed by the GNAT team at New York University. --
28 -- Extensive contributions were provided by Ada Core Technologies Inc. --
29 -- --
30 ------------------------------------------------------------------------------
32 -- This package provides an interface to the sockets communication facility
33 -- provided on many operating systems. This is implemented on the following
34 -- platforms:
36 -- All native ports, with restrictions as follows
38 -- Multicast is available only on systems which provide support for this
39 -- feature, so it is not available if Multicast is not supported, or not
40 -- installed.
42 -- VxWorks cross ports fully implement this package
44 -- This package is not yet implemented on LynxOS or other cross ports
46 with Ada.Exceptions;
47 with Ada.Streams;
48 with Ada.Strings.Unbounded;
49 with Ada.Unchecked_Deallocation;
51 with Interfaces.C;
53 with System.OS_Constants;
54 with System.Storage_Elements;
56 package GNAT.Sockets is
58 -- Sockets are designed to provide a consistent communication facility
59 -- between applications. This package provides an Ada binding to the
60 -- de-facto standard BSD sockets API. The documentation below covers
61 -- only the specific binding provided by this package. It assumes that
62 -- the reader is already familiar with general network programming and
63 -- sockets usage. A useful reference on this matter is W. Richard Stevens'
64 -- "UNIX Network Programming: The Sockets Networking API"
65 -- (ISBN: 0131411551).
67 -- GNAT.Sockets has been designed with several ideas in mind
69 -- This is a system independent interface. Therefore, we try as much as
70 -- possible to mask system incompatibilities. Some functionalities are not
71 -- available because there are not fully supported on some systems.
73 -- This is a thick binding. For instance, a major effort has been done to
74 -- avoid using memory addresses or untyped ints. We preferred to define
75 -- streams and enumeration types. Errors are not returned as returned
76 -- values but as exceptions.
78 -- This package provides a POSIX-compliant interface (between two
79 -- different implementations of the same routine, we adopt the one closest
80 -- to the POSIX specification). For instance, using select(), the
81 -- notification of an asynchronous connect failure is delivered in the
82 -- write socket set (POSIX) instead of the exception socket set (NT).
84 -- The example below demonstrates various features of GNAT.Sockets:
86 -- with GNAT.Sockets; use GNAT.Sockets;
88 -- with Ada.Text_IO;
89 -- with Ada.Exceptions; use Ada.Exceptions;
91 -- procedure PingPong is
93 -- Group : constant String := "239.255.128.128";
94 -- -- Multicast group: administratively scoped IP address
96 -- task Pong is
97 -- entry Start;
98 -- entry Stop;
99 -- end Pong;
101 -- task body Pong is
102 -- Address : Sock_Addr_Type;
103 -- Server : Socket_Type;
104 -- Socket : Socket_Type;
105 -- Channel : Stream_Access;
107 -- begin
108 -- -- Get an Internet address of a host (here the local host name).
109 -- -- Note that a host can have several addresses. Here we get
110 -- -- the first one which is supposed to be the official one.
112 -- Address.Addr := Addresses (Get_Host_By_Name (Host_Name), 1);
114 -- -- Get a socket address that is an Internet address and a port
116 -- Address.Port := 5876;
118 -- -- The first step is to create a socket. Once created, this
119 -- -- socket must be associated to with an address. Usually only a
120 -- -- server (Pong here) needs to bind an address explicitly. Most
121 -- -- of the time clients can skip this step because the socket
122 -- -- routines will bind an arbitrary address to an unbound socket.
124 -- Create_Socket (Server);
126 -- -- Allow reuse of local addresses
128 -- Set_Socket_Option
129 -- (Server,
130 -- Socket_Level,
131 -- (Reuse_Address, True));
133 -- Bind_Socket (Server, Address);
135 -- -- A server marks a socket as willing to receive connect events
137 -- Listen_Socket (Server);
139 -- -- Once a server calls Listen_Socket, incoming connects events
140 -- -- can be accepted. The returned Socket is a new socket that
141 -- -- represents the server side of the connection. Server remains
142 -- -- available to receive further connections.
144 -- accept Start;
146 -- Accept_Socket (Server, Socket, Address);
148 -- -- Return a stream associated to the connected socket
150 -- Channel := Stream (Socket);
152 -- -- Force Pong to block
154 -- delay 0.2;
156 -- -- Receive and print message from client Ping
158 -- declare
159 -- Message : String := String'Input (Channel);
161 -- begin
162 -- Ada.Text_IO.Put_Line (Message);
164 -- -- Send same message back to client Ping
166 -- String'Output (Channel, Message);
167 -- end;
169 -- Close_Socket (Server);
170 -- Close_Socket (Socket);
172 -- -- Part of the multicast example
174 -- -- Create a datagram socket to send connectionless, unreliable
175 -- -- messages of a fixed maximum length.
177 -- Create_Socket (Socket, Family_Inet, Socket_Datagram);
179 -- -- Allow reuse of local addresses
181 -- Set_Socket_Option
182 -- (Socket,
183 -- Socket_Level,
184 -- (Reuse_Address, True));
186 -- -- Controls the live time of the datagram to avoid it being
187 -- -- looped forever due to routing errors. Routers decrement
188 -- -- the TTL of every datagram as it traverses from one network
189 -- -- to another and when its value reaches 0 the packet is
190 -- -- dropped. Default is 1.
192 -- Set_Socket_Option
193 -- (Socket,
194 -- IP_Protocol_For_IP_Level,
195 -- (Multicast_TTL, 1));
197 -- -- Want the data you send to be looped back to your host
199 -- Set_Socket_Option
200 -- (Socket,
201 -- IP_Protocol_For_IP_Level,
202 -- (Multicast_Loop, True));
204 -- -- If this socket is intended to receive messages, bind it
205 -- -- to a given socket address.
207 -- Address.Addr := Any_Inet_Addr;
208 -- Address.Port := 55505;
210 -- Bind_Socket (Socket, Address);
212 -- -- Join a multicast group
214 -- -- Portability note: On Windows, this option may be set only
215 -- -- on a bound socket.
217 -- Set_Socket_Option
218 -- (Socket,
219 -- IP_Protocol_For_IP_Level,
220 -- (Add_Membership, Inet_Addr (Group), Any_Inet_Addr));
222 -- -- If this socket is intended to send messages, provide the
223 -- -- receiver socket address.
225 -- Address.Addr := Inet_Addr (Group);
226 -- Address.Port := 55506;
228 -- Channel := Stream (Socket, Address);
230 -- -- Receive and print message from client Ping
232 -- declare
233 -- Message : String := String'Input (Channel);
235 -- begin
236 -- -- Get the address of the sender
238 -- Address := Get_Address (Channel);
239 -- Ada.Text_IO.Put_Line (Message & " from " & Image (Address));
241 -- -- Send same message back to client Ping
243 -- String'Output (Channel, Message);
244 -- end;
246 -- Close_Socket (Socket);
248 -- accept Stop;
250 -- exception when E : others =>
251 -- Ada.Text_IO.Put_Line
252 -- (Exception_Name (E) & ": " & Exception_Message (E));
253 -- end Pong;
255 -- task Ping is
256 -- entry Start;
257 -- entry Stop;
258 -- end Ping;
260 -- task body Ping is
261 -- Address : Sock_Addr_Type;
262 -- Socket : Socket_Type;
263 -- Channel : Stream_Access;
265 -- begin
266 -- accept Start;
268 -- -- See comments in Ping section for the first steps
270 -- Address.Addr := Addresses (Get_Host_By_Name (Host_Name), 1);
271 -- Address.Port := 5876;
272 -- Create_Socket (Socket);
274 -- Set_Socket_Option
275 -- (Socket,
276 -- Socket_Level,
277 -- (Reuse_Address, True));
279 -- -- Force Ping to block
281 -- delay 0.2;
283 -- -- If the client's socket is not bound, Connect_Socket will
284 -- -- bind to an unused address. The client uses Connect_Socket to
285 -- -- create a logical connection between the client's socket and
286 -- -- a server's socket returned by Accept_Socket.
288 -- Connect_Socket (Socket, Address);
290 -- Channel := Stream (Socket);
292 -- -- Send message to server Pong
294 -- String'Output (Channel, "Hello world");
296 -- -- Force Ping to block
298 -- delay 0.2;
300 -- -- Receive and print message from server Pong
302 -- Ada.Text_IO.Put_Line (String'Input (Channel));
303 -- Close_Socket (Socket);
305 -- -- Part of multicast example. Code similar to Pong's one
307 -- Create_Socket (Socket, Family_Inet, Socket_Datagram);
309 -- Set_Socket_Option
310 -- (Socket,
311 -- Socket_Level,
312 -- (Reuse_Address, True));
314 -- Set_Socket_Option
315 -- (Socket,
316 -- IP_Protocol_For_IP_Level,
317 -- (Multicast_TTL, 1));
319 -- Set_Socket_Option
320 -- (Socket,
321 -- IP_Protocol_For_IP_Level,
322 -- (Multicast_Loop, True));
324 -- Address.Addr := Any_Inet_Addr;
325 -- Address.Port := 55506;
327 -- Bind_Socket (Socket, Address);
329 -- Set_Socket_Option
330 -- (Socket,
331 -- IP_Protocol_For_IP_Level,
332 -- (Add_Membership, Inet_Addr (Group), Any_Inet_Addr));
334 -- Address.Addr := Inet_Addr (Group);
335 -- Address.Port := 55505;
337 -- Channel := Stream (Socket, Address);
339 -- -- Send message to server Pong
341 -- String'Output (Channel, "Hello world");
343 -- -- Receive and print message from server Pong
345 -- declare
346 -- Message : String := String'Input (Channel);
348 -- begin
349 -- Address := Get_Address (Channel);
350 -- Ada.Text_IO.Put_Line (Message & " from " & Image (Address));
351 -- end;
353 -- Close_Socket (Socket);
355 -- accept Stop;
357 -- exception when E : others =>
358 -- Ada.Text_IO.Put_Line
359 -- (Exception_Name (E) & ": " & Exception_Message (E));
360 -- end Ping;
362 -- begin
363 -- Initialize;
364 -- Ping.Start;
365 -- Pong.Start;
366 -- Ping.Stop;
367 -- Pong.Stop;
368 -- Finalize;
369 -- end PingPong;
371 package SOSC renames System.OS_Constants;
372 -- Renaming used to provide short-hand notations throughout the sockets
373 -- binding. Note that System.OS_Constants is an internal unit, and the
374 -- entities declared therein are not meant for direct access by users,
375 -- including through this renaming.
377 use type Interfaces.C.int;
378 -- Need visibility on "-" operator so that we can write -1
380 procedure Initialize;
381 pragma Obsolescent
382 (Entity => Initialize,
383 Message => "explicit initialization is no longer required");
384 -- Initialize must be called before using any other socket routines.
385 -- Note that this operation is a no-op on UNIX platforms, but applications
386 -- should make sure to call it if portability is expected: some platforms
387 -- (such as Windows) require initialization before any socket operation.
388 -- This is now a no-op (initialization and finalization are done
389 -- automatically).
391 procedure Initialize (Process_Blocking_IO : Boolean);
392 pragma Obsolescent
393 (Entity => Initialize,
394 Message => "passing a parameter to Initialize is no longer supported");
395 -- Previous versions of GNAT.Sockets used to require the user to indicate
396 -- whether socket I/O was process- or thread-blocking on the platform.
397 -- This property is now determined automatically when the run-time library
398 -- is built. The old version of Initialize, taking a parameter, is kept
399 -- for compatibility reasons, but this interface is obsolete (and if the
400 -- value given is wrong, an exception will be raised at run time).
401 -- This is now a no-op (initialization and finalization are done
402 -- automatically).
404 procedure Finalize;
405 pragma Obsolescent
406 (Entity => Finalize,
407 Message => "explicit finalization is no longer required");
408 -- After Finalize is called it is not possible to use any routines
409 -- exported in by this package. This procedure is idempotent.
410 -- This is now a no-op (initialization and finalization are done
411 -- automatically).
413 type Socket_Type is private;
414 -- Sockets are used to implement a reliable bi-directional point-to-point,
415 -- stream-based connections between hosts. No_Socket provides a special
416 -- value to denote uninitialized sockets.
418 No_Socket : constant Socket_Type;
420 type Selector_Type is limited private;
421 type Selector_Access is access all Selector_Type;
422 -- Selector objects are used to wait for i/o events to occur on sockets
424 Null_Selector : constant Selector_Type;
425 -- The Null_Selector can be used in place of a normal selector without
426 -- having to call Create_Selector if the use of Abort_Selector is not
427 -- required.
429 -- Timeval_Duration is a subtype of Standard.Duration because the full
430 -- range of Standard.Duration cannot be represented in the equivalent C
431 -- structure (struct timeval). Moreover, negative values are not allowed
432 -- to avoid system incompatibilities.
434 Immediate : constant Duration := 0.0;
436 Forever : constant Duration :=
437 Duration'Min
438 (Duration'Last,
439 (if SOSC."=" (SOSC.Target_OS, SOSC.Windows)
440 then Duration (2 ** 32 / 1000)
441 else 1.0 * SOSC.MAX_tv_sec));
442 -- Largest possible Duration that is also a valid value for the OS type
443 -- used for socket timeout.
445 subtype Timeval_Duration is Duration range Immediate .. Forever;
447 subtype Selector_Duration is Timeval_Duration;
448 -- Timeout value for selector operations
450 type Selector_Status is (Completed, Expired, Aborted);
451 -- Completion status of a selector operation, indicated as follows:
452 -- Completed: one of the expected events occurred
453 -- Expired: no event occurred before the expiration of the timeout
454 -- Aborted: an external action cancelled the wait operation before
455 -- any event occurred.
457 Socket_Error : exception;
458 -- There is only one exception in this package to deal with an error during
459 -- a socket routine. Once raised, its message contains a string describing
460 -- the error code.
462 function Image (Socket : Socket_Type) return String;
463 -- Return a printable string for Socket
465 function To_Ada (Fd : Integer) return Socket_Type with Inline;
466 -- Convert a file descriptor to Socket_Type. This is useful when a socket
467 -- file descriptor is obtained from an external library call.
469 function To_C (Socket : Socket_Type) return Integer with Inline;
470 -- Return a file descriptor to be used by external subprograms. This is
471 -- useful for C functions that are not yet interfaced in this package.
473 type Family_Type is (Family_Inet, Family_Inet6, Family_Unix, Family_Unspec);
474 -- Address family (or protocol family) identifies the communication domain
475 -- and groups protocols with similar address formats.
476 -- The order of the enumeration elements should not be changed unilaterally
477 -- because the IPv6_TCP_Preferred routine rely on it.
479 subtype Family_Inet_4_6 is Family_Type range Family_Inet .. Family_Inet6;
481 type Mode_Type is (Socket_Stream, Socket_Datagram, Socket_Raw);
482 -- Stream sockets provide connection-oriented byte streams. Datagram
483 -- sockets support unreliable connectionless message-based communication.
484 -- Raw sockets provide raw network-protocol access.
485 -- The order of the enumeration elements should not be changed unilaterally
486 -- because the IPv6_TCP_Preferred routine relies on it.
488 type Shutmode_Type is (Shut_Read, Shut_Write, Shut_Read_Write);
489 -- When a process closes a socket, the policy is to retain any data queued
490 -- until either a delivery or a timeout expiration (in this case, the data
491 -- are discarded). Finer control is available through shutdown. With
492 -- Shut_Read, no more data can be received from the socket. With_Write, no
493 -- more data can be transmitted. Neither transmission nor reception can be
494 -- performed with Shut_Read_Write.
496 type Port_Type is range 0 .. 16#ffff#;
497 -- TCP/UDP port number
499 Any_Port : constant Port_Type;
500 -- All ports
502 No_Port : constant Port_Type;
503 -- Uninitialized port number
505 type Inet_Addr_Comp_Type is mod 2 ** 8;
506 -- Octet for Internet address
508 Inet_Addr_Bytes_Length : constant array (Family_Inet_4_6) of Natural :=
509 [Family_Inet => 4, Family_Inet6 => 16];
511 type Inet_Addr_Bytes is array (Natural range <>) of Inet_Addr_Comp_Type;
513 subtype Inet_Addr_V4_Type is
514 Inet_Addr_Bytes (1 .. Inet_Addr_Bytes_Length (Family_Inet));
515 subtype Inet_Addr_V6_Type is
516 Inet_Addr_Bytes (1 .. Inet_Addr_Bytes_Length (Family_Inet6));
518 subtype Inet_Addr_VN_Type is Inet_Addr_Bytes;
519 -- For backwards compatibility
521 type Inet_Addr_Type (Family : Family_Inet_4_6 := Family_Inet) is record
522 case Family is
523 when Family_Inet =>
524 Sin_V4 : Inet_Addr_V4_Type := [others => 0];
526 when Family_Inet6 =>
527 Sin_V6 : Inet_Addr_V6_Type := [others => 0];
529 end case;
530 end record;
532 -- An Internet address depends on an address family (IPv4 contains 4 octets
533 -- and IPv6 contains 16 octets).
535 Any_Inet_Addr : constant Inet_Addr_Type;
536 -- Wildcard enabling all addresses to use with bind
538 Any_Inet6_Addr : constant Inet_Addr_Type;
539 -- Idem for IPV6 socket
541 No_Inet_Addr : constant Inet_Addr_Type;
542 -- Uninitialized inet address
544 Broadcast_Inet_Addr : constant Inet_Addr_Type;
545 -- Broadcast destination address in the current network
547 Loopback_Inet_Addr : constant Inet_Addr_Type;
548 -- Loopback address to the local host
550 Loopback_Inet6_Addr : constant Inet_Addr_Type;
551 -- IPv6 Loopback address to the local host
553 -- Useful constants for multicast addresses
555 Unspecified_Group_Inet_Addr : constant Inet_Addr_Type;
556 -- IPv4 multicast mask with prefix length 4
558 Unspecified_Group_Inet6_Addr : constant Inet_Addr_Type;
559 -- IPv6 multicast mask with prefix length 16
561 All_Hosts_Group_Inet_Addr : constant Inet_Addr_Type;
562 -- Multicast group addresses all hosts on the same network segment
564 All_Hosts_Group_Inet6_Addr : constant Inet_Addr_Type;
565 -- Idem for IPv6 protocol
567 All_Routers_Group_Inet_Addr : constant Inet_Addr_Type;
568 -- Multicast group addresses all routers on the same network segment
570 All_Routers_Group_Inet6_Addr : constant Inet_Addr_Type;
571 -- Idem for IPv6 protocol
573 IPv4_To_IPv6_Prefix : constant Inet_Addr_Bytes :=
574 [1 .. 10 => 0, 11 .. 12 => 255];
575 -- Prefix for IPv4 mapped to IPv6 addresses
577 -- Functions to handle masks and prefixes
579 function Mask
580 (Family : Family_Inet_4_6;
581 Length : Natural;
582 Host : Boolean := False) return Inet_Addr_Type;
583 -- Return an address mask of the given family with the given prefix length.
584 -- If Host is False, this is a network mask (i.e. network bits are 1,
585 -- and host bits are 0); if Host is True, this is a host mask (i.e.
586 -- network bits are 0, and host bits are 1).
588 function "and" (Addr, Mask : Inet_Addr_Type) return Inet_Addr_Type;
589 function "or" (Net, Host : Inet_Addr_Type) return Inet_Addr_Type;
590 function "not" (Mask : Inet_Addr_Type) return Inet_Addr_Type;
591 -- Bit-wise operations on inet addresses (both operands must have the
592 -- same address family).
594 type Sock_Addr_Type (Family : Family_Type := Family_Inet) is record
595 case Family is
596 when Family_Unix =>
597 Name : Ada.Strings.Unbounded.Unbounded_String;
598 when Family_Inet_4_6 =>
599 Addr : Inet_Addr_Type (Family);
600 Port : Port_Type;
601 when Family_Unspec =>
602 null;
603 end case;
604 end record;
605 pragma No_Component_Reordering (Sock_Addr_Type);
606 -- Socket addresses fully define a socket connection with protocol family,
607 -- an Internet address and a port. No_Sock_Addr provides a special value
608 -- for uninitialized socket addresses.
610 No_Sock_Addr : constant Sock_Addr_Type;
611 -- Uninitialized socket address
613 function Is_IPv4_Address (Name : String) return Boolean;
614 -- Return true when Name is an IPv4 address in dotted quad notation
616 function Is_IPv6_Address (Name : String) return Boolean;
617 -- Return true when Name is an IPv6 address in numeric format
619 function Image (Value : Inet_Addr_Type) return String;
620 -- Return an image of an Internet address. IPv4 notation consists in 4
621 -- octets in decimal format separated by dots. IPv6 notation consists in
622 -- 8 hextets in hexadecimal format separated by colons.
624 function Image (Value : Sock_Addr_Type) return String;
625 -- Return socket address image. Network socket address image will be with
626 -- a port image separated by a colon.
628 function Inet_Addr (Image : String) return Inet_Addr_Type;
629 -- Convert address image from numbers-dots-and-colons notation into an
630 -- inet address.
632 function Unix_Socket_Address (Addr : String) return Sock_Addr_Type;
633 -- Convert unix local socket name to Sock_Addr_Type
635 function Network_Socket_Address
636 (Addr : Inet_Addr_Type; Port : Port_Type) return Sock_Addr_Type;
637 -- Create network socket address
639 -- Host entries provide complete information on a given host: the official
640 -- name, an array of alternative names or aliases and array of network
641 -- addresses.
643 type Host_Entry_Type
644 (Aliases_Length, Addresses_Length : Natural) is private;
646 function Official_Name (E : Host_Entry_Type) return String;
647 -- Return official name in host entry
649 function Aliases_Length (E : Host_Entry_Type) return Natural;
650 -- Return number of aliases in host entry
652 function Addresses_Length (E : Host_Entry_Type) return Natural;
653 -- Return number of addresses in host entry
655 function Aliases
656 (E : Host_Entry_Type;
657 N : Positive := 1) return String;
658 -- Return N'th aliases in host entry. The first index is 1
660 function Addresses
661 (E : Host_Entry_Type;
662 N : Positive := 1) return Inet_Addr_Type;
663 -- Return N'th addresses in host entry. The first index is 1
665 Host_Error : exception;
666 -- Exception raised by the two following procedures. Once raised, its
667 -- message contains a string describing the error code. This exception is
668 -- raised when an host entry cannot be retrieved.
670 function Get_Host_By_Address
671 (Address : Inet_Addr_Type;
672 Family : Family_Type := Family_Inet) return Host_Entry_Type;
673 -- Return host entry structure for the given Inet address. Note that no
674 -- result will be returned if there is no mapping of this IP address to a
675 -- host name in the system tables (host database, DNS or otherwise).
677 function Get_Host_By_Name
678 (Name : String) return Host_Entry_Type;
679 -- Return host entry structure for the given host name. Here name is
680 -- either a host name, or an IP address. If Name is an IP address, this
681 -- is equivalent to Get_Host_By_Address (Inet_Addr (Name)).
683 function Host_Name return String;
684 -- Return the name of the current host
686 type Service_Entry_Type (Aliases_Length : Natural) is private;
687 -- Service entries provide complete information on a given service: the
688 -- official name, an array of alternative names or aliases and the port
689 -- number.
691 function Official_Name (S : Service_Entry_Type) return String;
692 -- Return official name in service entry
694 function Port_Number (S : Service_Entry_Type) return Port_Type;
695 -- Return port number in service entry
697 function Protocol_Name (S : Service_Entry_Type) return String;
698 -- Return Protocol in service entry (usually UDP or TCP)
700 function Aliases_Length (S : Service_Entry_Type) return Natural;
701 -- Return number of aliases in service entry
703 function Aliases
704 (S : Service_Entry_Type;
705 N : Positive := 1) return String;
706 -- Return N'th aliases in service entry (the first index is 1)
708 function Get_Service_By_Name
709 (Name : String;
710 Protocol : String) return Service_Entry_Type;
711 -- Return service entry structure for the given service name
713 function Get_Service_By_Port
714 (Port : Port_Type;
715 Protocol : String) return Service_Entry_Type;
716 -- Return service entry structure for the given service port number
718 Service_Error : exception;
719 -- Comment required ???
721 -- Errors are described by an enumeration type. There is only one exception
722 -- Socket_Error in this package to deal with an error during a socket
723 -- routine. Once raised, its message contains the error code between
724 -- brackets and a string describing the error code.
726 -- The name of the enumeration constant documents the error condition
727 -- Note that on some platforms, a single error value is used for both
728 -- EWOULDBLOCK and EAGAIN. Both errors are therefore always reported as
729 -- Resource_Temporarily_Unavailable.
731 type Error_Type is
732 (Success,
733 Permission_Denied,
734 Address_Already_In_Use,
735 Cannot_Assign_Requested_Address,
736 Address_Family_Not_Supported_By_Protocol,
737 Operation_Already_In_Progress,
738 Bad_File_Descriptor,
739 Software_Caused_Connection_Abort,
740 Connection_Refused,
741 Connection_Reset_By_Peer,
742 Destination_Address_Required,
743 Bad_Address,
744 Host_Is_Down,
745 No_Route_To_Host,
746 Operation_Now_In_Progress,
747 Interrupted_System_Call,
748 Invalid_Argument,
749 Input_Output_Error,
750 Transport_Endpoint_Already_Connected,
751 Too_Many_Symbolic_Links,
752 Too_Many_Open_Files,
753 Message_Too_Long,
754 File_Name_Too_Long,
755 Network_Is_Down,
756 Network_Dropped_Connection_Because_Of_Reset,
757 Network_Is_Unreachable,
758 No_Buffer_Space_Available,
759 Protocol_Not_Available,
760 Transport_Endpoint_Not_Connected,
761 Socket_Operation_On_Non_Socket,
762 Operation_Not_Supported,
763 Protocol_Family_Not_Supported,
764 Protocol_Not_Supported,
765 Protocol_Wrong_Type_For_Socket,
766 Cannot_Send_After_Transport_Endpoint_Shutdown,
767 Socket_Type_Not_Supported,
768 Connection_Timed_Out,
769 Too_Many_References,
770 Resource_Temporarily_Unavailable,
771 Broken_Pipe,
772 Unknown_Host,
773 Host_Name_Lookup_Failure,
774 Non_Recoverable_Error,
775 Unknown_Server_Error,
776 Cannot_Resolve_Error);
778 -- Get_Socket_Options and Set_Socket_Options manipulate options associated
779 -- with a socket. Options may exist at multiple protocol levels in the
780 -- communication stack. Socket_Level is the uppermost socket level.
782 type Level_Type is
783 (Socket_Level,
784 IP_Protocol_For_IP_Level,
785 IP_Protocol_For_IPv6_Level,
786 IP_Protocol_For_UDP_Level,
787 IP_Protocol_For_TCP_Level,
788 IP_Protocol_For_ICMP_Level,
789 IP_Protocol_For_IGMP_Level,
790 IP_Protocol_For_RAW_Level);
792 -- There are several options available to manipulate sockets. Each option
793 -- has a name and several values available. Most of the time, the value
794 -- is a boolean to enable or disable this option. Each socket option is
795 -- provided with an appropriate C name taken from the sockets API comments.
796 -- The C name can be used to find a detailed description in the OS-specific
797 -- documentation. The options are grouped by main Level_Type value, which
798 -- can be used together with this option in calls to the Set_Socket_Option
799 -- and Get_Socket_Option routines. Note that some options can be used with
800 -- more than one level.
802 type Option_Name is
803 (Generic_Option,
804 -- Can be used to set/get any socket option via an OS-specific option
805 -- code with an integer value.
807 ------------------
808 -- Socket_Level --
809 ------------------
811 Keep_Alive, -- SO_KEEPALIVE
812 -- Enable sending of keep-alive messages on connection-oriented sockets
814 Reuse_Address, -- SO_REUSEADDR
815 -- Enable binding to an address and port already in use
817 Broadcast, -- SO_BROADCAST
818 -- Enable sending broadcast datagrams on the socket
820 Send_Buffer, -- SO_SNDBUF
821 -- Set/get the maximum socket send buffer in bytes
823 Receive_Buffer, -- SO_RCVBUF
824 -- Set/get the maximum socket receive buffer in bytes
826 Linger, -- SO_LINGER
827 -- When enabled, a Close_Socket or Shutdown_Socket will wait until all
828 -- queued messages for the socket have been successfully sent or the
829 -- linger timeout has been reached.
831 Error, -- SO_ERROR
832 -- Get and clear the pending socket error integer code
834 Send_Timeout, -- SO_SNDTIMEO
835 -- Specify sending timeout until reporting an error
837 Receive_Timeout, -- SO_RCVTIMEO
838 -- Specify receiving timeout until reporting an error
840 Busy_Polling, -- SO_BUSY_POLL
841 -- Sets the approximate time in microseconds to busy poll on a blocking
842 -- receive when there is no data.
844 -------------------------------
845 -- IP_Protocol_For_TCP_Level --
846 -------------------------------
848 No_Delay, -- TCP_NODELAY
849 -- Disable the Nagle algorithm. This means that output buffer content
850 -- is always sent as soon as possible, even if there is only a small
851 -- amount of data.
853 Keep_Alive_Count, -- TCP_KEEPCNT
854 -- Maximum number of keepalive probes
856 Keep_Alive_Idle, -- TCP_KEEPIDLE
857 -- Idle time before TCP starts sending keepalive probes
859 Keep_Alive_Interval, -- TCP_KEEPINTVL
860 -- Time between individual keepalive probes
862 ------------------------------
863 -- IP_Protocol_For_IP_Level --
864 ------------------------------
866 Add_Membership_V4, -- IP_ADD_MEMBERSHIP
867 -- Join a multicast group
869 Drop_Membership_V4, -- IP_DROP_MEMBERSHIP
870 -- Leave a multicast group
872 Multicast_If_V4, -- IP_MULTICAST_IF
873 -- Set/Get outgoing interface for sending multicast packets
875 Multicast_Loop_V4, -- IP_MULTICAST_LOOP
876 -- This boolean option determines whether sent multicast packets should
877 -- be looped back to the local sockets.
879 Multicast_TTL, -- IP_MULTICAST_TTL
880 -- Set/Get the time-to-live of sent multicast packets
882 Receive_Packet_Info, -- IP_PKTINFO
883 -- Receive low-level packet info as ancillary data
885 --------------------------------
886 -- IP_Protocol_For_IPv6_Level --
887 --------------------------------
889 Add_Membership_V6, -- IPV6_ADD_MEMBERSHIP
890 -- Join IPv6 multicast group
892 Drop_Membership_V6, -- IPV6_DROP_MEMBERSHIP
893 -- Leave IPv6 multicast group
895 Multicast_If_V6, -- IPV6_MULTICAST_IF
896 -- Set/Get outgoing interface index for sending multicast packets
898 Multicast_Loop_V6, -- IPV6_MULTICAST_LOOP
899 -- This boolean option determines whether sent multicast IPv6 packets
900 -- should be looped back to the local sockets.
902 IPv6_Only, -- IPV6_V6ONLY
903 -- Restricted to IPv6 communications only
905 Multicast_Hops -- IPV6_MULTICAST_HOPS
906 -- Set the multicast hop limit for the IPv6 socket
909 subtype Specific_Option_Name is
910 Option_Name range Keep_Alive .. Option_Name'Last;
912 Add_Membership : Option_Name renames Add_Membership_V4;
913 Drop_Membership : Option_Name renames Drop_Membership_V4;
914 Multicast_If : Option_Name renames Multicast_If_V4;
915 Multicast_Loop : Option_Name renames Multicast_Loop_V4;
917 type Option_Type (Name : Option_Name := Keep_Alive) is record
918 case Name is
919 when Generic_Option =>
920 Optname : Interfaces.C.int := -1;
921 Optval : Interfaces.C.int;
923 when Keep_Alive |
924 Reuse_Address |
925 Broadcast |
926 Linger |
927 No_Delay |
928 Receive_Packet_Info |
929 IPv6_Only |
930 Multicast_Loop_V4 |
931 Multicast_Loop_V6 =>
932 Enabled : Boolean;
934 case Name is
935 when Linger =>
936 Seconds : Natural;
937 when others =>
938 null;
939 end case;
941 when Keep_Alive_Count =>
942 Count : Natural;
944 when Keep_Alive_Idle =>
945 Idle_Seconds : Natural;
947 when Keep_Alive_Interval =>
948 Interval_Seconds : Natural;
950 when Busy_Polling =>
951 Microseconds : Natural;
953 when Send_Buffer |
954 Receive_Buffer =>
955 Size : Natural;
957 when Error =>
958 Error : Error_Type;
960 when Add_Membership_V4 |
961 Add_Membership_V6 |
962 Drop_Membership_V4 |
963 Drop_Membership_V6 =>
964 Multicast_Address : Inet_Addr_Type;
965 case Name is
966 when Add_Membership_V4 |
967 Drop_Membership_V4 =>
968 Local_Interface : Inet_Addr_Type;
969 when others =>
970 Interface_Index : Natural;
971 end case;
973 when Multicast_If_V4 =>
974 Outgoing_If : Inet_Addr_Type;
976 when Multicast_If_V6 =>
977 Outgoing_If_Index : Natural;
979 when Multicast_TTL =>
980 Time_To_Live : Natural;
982 when Multicast_Hops =>
983 Hop_Limit : Integer range -1 .. 255;
985 when Send_Timeout |
986 Receive_Timeout =>
987 Timeout : Timeval_Duration;
989 end case;
990 end record;
992 -- There are several controls available to manipulate sockets. Each option
993 -- has a name and several values available. These controls differ from the
994 -- socket options in that they are not specific to sockets but are
995 -- available for any device.
997 type Request_Name is
998 (Non_Blocking_IO, -- Cause a caller not to wait on blocking operations
999 N_Bytes_To_Read); -- Return the number of bytes available to read
1001 type Request_Type (Name : Request_Name := Non_Blocking_IO) is record
1002 case Name is
1003 when Non_Blocking_IO =>
1004 Enabled : Boolean;
1006 when N_Bytes_To_Read =>
1007 Size : Natural;
1009 end case;
1010 end record;
1012 -- A request flag allows specification of the type of message transmissions
1013 -- or receptions. A request flag can be combination of zero or more
1014 -- predefined request flags.
1016 type Request_Flag_Type is private;
1018 No_Request_Flag : constant Request_Flag_Type;
1019 -- This flag corresponds to the normal execution of an operation
1021 Process_Out_Of_Band_Data : constant Request_Flag_Type;
1022 -- This flag requests that the receive or send function operates on
1023 -- out-of-band data when the socket supports this notion (e.g.
1024 -- Socket_Stream).
1026 Peek_At_Incoming_Data : constant Request_Flag_Type;
1027 -- This flag causes the receive operation to return data from the beginning
1028 -- of the receive queue without removing that data from the queue. A
1029 -- subsequent receive call will return the same data.
1031 Wait_For_A_Full_Reception : constant Request_Flag_Type;
1032 -- This flag requests that the operation block until the full request is
1033 -- satisfied. However, the call may still return less data than requested
1034 -- if a signal is caught, an error or disconnect occurs, or the next data
1035 -- to be received is of a different type than that returned. Note that
1036 -- this flag depends on support in the underlying sockets implementation,
1037 -- and is not supported under Windows.
1039 Send_End_Of_Record : constant Request_Flag_Type;
1040 -- This flag indicates that the entire message has been sent and so this
1041 -- terminates the record.
1043 function "+" (L, R : Request_Flag_Type) return Request_Flag_Type;
1044 -- Combine flag L with flag R
1046 type Stream_Element_Reference is access all Ada.Streams.Stream_Element;
1048 type Vector_Element is record
1049 Base : Stream_Element_Reference;
1050 Length : Interfaces.C.size_t;
1051 end record;
1053 type Vector_Type is array (Integer range <>) of Vector_Element;
1055 type Address_Info is record
1056 Addr : Sock_Addr_Type;
1057 Mode : Mode_Type := Socket_Stream;
1058 Level : Level_Type := IP_Protocol_For_IP_Level;
1059 end record;
1061 type Address_Info_Array is array (Positive range <>) of Address_Info;
1063 function Get_Address_Info
1064 (Host : String;
1065 Service : String;
1066 Family : Family_Type := Family_Unspec;
1067 Mode : Mode_Type := Socket_Stream;
1068 Level : Level_Type := IP_Protocol_For_IP_Level;
1069 Numeric_Host : Boolean := False;
1070 Passive : Boolean := False;
1071 Unknown : access procedure
1072 (Family, Mode, Level, Length : Integer) := null)
1073 return Address_Info_Array;
1074 -- Returns available addresses for the Host and Service names.
1075 -- If Family is Family_Unspec, all available protocol families returned.
1076 -- Service is the name of service as defined in /etc/services or port
1077 -- number in string representation.
1078 -- If Unknown procedure access specified it will be called in case of
1079 -- unknown family found.
1080 -- Numeric_Host flag suppresses any potentially lengthy network host
1081 -- address lookups, and Host have to represent numerical network address in
1082 -- this case.
1083 -- If Passive is True and Host is empty then the returned socket addresses
1084 -- will be suitable for binding a socket that will accept connections.
1085 -- The returned socket address will contain the "wildcard address".
1086 -- The wildcard address is used by applications (typically servers) that
1087 -- intend to accept connections on any of the hosts's network addresses.
1088 -- If Host is not empty, then the Passive flag is ignored.
1089 -- If Passive is False, then the returned socket addresses will be suitable
1090 -- for use with connect, sendto, or sendmsg. If Host is empty, then the
1091 -- network address will be set to the loopback interface address;
1092 -- this is used by applications that intend to communicate with peers
1093 -- running on the same host.
1095 procedure Sort
1096 (Addr_Info : in out Address_Info_Array;
1097 Compare : access function (Left, Right : Address_Info) return Boolean);
1098 -- Sort address info array in order defined by compare function
1100 function IPv6_TCP_Preferred (Left, Right : Address_Info) return Boolean;
1101 -- To use with Sort to order where IPv6 and TCP addresses first
1103 type Host_Service (Host_Length, Service_Length : Natural) is record
1104 Host : String (1 .. Host_Length);
1105 Service : String (1 .. Service_Length);
1106 end record;
1108 function Get_Name_Info
1109 (Addr : Sock_Addr_Type;
1110 Numeric_Host : Boolean := False;
1111 Numeric_Serv : Boolean := False) return Host_Service;
1112 -- Returns host and service names by the address and port.
1113 -- If Numeric_Host is True, then the numeric form of the hostname is
1114 -- returned. When Numeric_Host is False, this will still happen in case the
1115 -- host name cannot be determined.
1116 -- If Numenric_Serv is True, then the numeric form of the service address
1117 -- (port number) is returned. When Numenric_Serv is False, this will still
1118 -- happen in case the service's name cannot be determined.
1120 procedure Create_Socket
1121 (Socket : out Socket_Type;
1122 Family : Family_Type := Family_Inet;
1123 Mode : Mode_Type := Socket_Stream;
1124 Level : Level_Type := IP_Protocol_For_IP_Level);
1125 -- Create an endpoint for communication. Raises Socket_Error on error
1127 procedure Create_Socket_Pair
1128 (Left : out Socket_Type;
1129 Right : out Socket_Type;
1130 Family : Family_Type := Family_Unspec;
1131 Mode : Mode_Type := Socket_Stream;
1132 Level : Level_Type := IP_Protocol_For_IP_Level);
1133 -- Create two connected sockets. Raises Socket_Error on error.
1134 -- If Family is unspecified, it creates Family_Unix sockets on UNIX and
1135 -- Family_Inet sockets on non UNIX platforms.
1137 procedure Accept_Socket
1138 (Server : Socket_Type;
1139 Socket : out Socket_Type;
1140 Address : out Sock_Addr_Type);
1141 -- Extracts the first connection request on the queue of pending
1142 -- connections, creates a new connected socket with mostly the same
1143 -- properties as Server, and allocates a new socket. The returned Address
1144 -- is filled in with the address of the connection. Raises Socket_Error on
1145 -- error. Note: if Server is a non-blocking socket, whether or not this
1146 -- aspect is inherited by Socket is platform-dependent.
1148 procedure Accept_Socket
1149 (Server : Socket_Type;
1150 Socket : out Socket_Type;
1151 Address : out Sock_Addr_Type;
1152 Timeout : Selector_Duration;
1153 Selector : access Selector_Type := null;
1154 Status : out Selector_Status);
1155 -- Accept a new connection on Server using Accept_Socket, waiting no longer
1156 -- than the given timeout duration. Status is set to indicate whether the
1157 -- operation completed successfully, timed out, or was aborted. If Selector
1158 -- is not null, the designated selector is used to wait for the socket to
1159 -- become available, else a private selector object is created by this
1160 -- procedure and destroyed before it returns.
1162 procedure Bind_Socket
1163 (Socket : Socket_Type;
1164 Address : Sock_Addr_Type);
1165 -- Once a socket is created, assign a local address to it. Raise
1166 -- Socket_Error on error.
1168 procedure Close_Socket (Socket : Socket_Type);
1169 -- Close a socket and more specifically a non-connected socket
1171 procedure Connect_Socket
1172 (Socket : Socket_Type;
1173 Server : Sock_Addr_Type);
1174 -- Make a connection to another socket which has the address of Server.
1175 -- Raises Socket_Error on error.
1177 procedure Connect_Socket
1178 (Socket : Socket_Type;
1179 Server : Sock_Addr_Type;
1180 Timeout : Selector_Duration;
1181 Selector : access Selector_Type := null;
1182 Status : out Selector_Status);
1183 -- Connect Socket to the given Server address using Connect_Socket, waiting
1184 -- no longer than the given timeout duration. Status is set to indicate
1185 -- whether the operation completed successfully, timed out, or was aborted.
1186 -- If Selector is not null, the designated selector is used to wait for the
1187 -- socket to become available, else a private selector object is created
1188 -- by this procedure and destroyed before it returns. If Timeout is 0.0,
1189 -- no attempt is made to detect whether the connection has succeeded; it
1190 -- is up to the user to determine this using Check_Selector later on.
1192 procedure Control_Socket
1193 (Socket : Socket_Type;
1194 Request : in out Request_Type);
1195 -- Obtain or set parameter values that control the socket. This control
1196 -- differs from the socket options in that they are not specific to sockets
1197 -- but are available for any device.
1199 function Get_Peer_Name (Socket : Socket_Type) return Sock_Addr_Type;
1200 -- Return the peer or remote socket address of a socket. Raise
1201 -- Socket_Error on error.
1203 function Get_Socket_Name (Socket : Socket_Type) return Sock_Addr_Type;
1204 -- Return the local or current socket address of a socket. Return
1205 -- No_Sock_Addr on error (e.g. socket closed or not locally bound).
1207 function Get_Socket_Option
1208 (Socket : Socket_Type;
1209 Level : Level_Type;
1210 Name : Option_Name;
1211 Optname : Interfaces.C.int := -1) return Option_Type;
1212 -- Get the options associated with a socket. Raises Socket_Error on error.
1213 -- Optname identifies specific option when Name is Generic_Option.
1215 procedure Listen_Socket
1216 (Socket : Socket_Type;
1217 Length : Natural := 15);
1218 -- To accept connections, a socket is first created with Create_Socket,
1219 -- a willingness to accept incoming connections and a queue Length for
1220 -- incoming connections are specified. Raise Socket_Error on error.
1221 -- The queue length of 15 is an example value that should be appropriate
1222 -- in usual cases. It can be adjusted according to each application's
1223 -- particular requirements.
1225 procedure Receive_Socket
1226 (Socket : Socket_Type;
1227 Item : out Ada.Streams.Stream_Element_Array;
1228 Last : out Ada.Streams.Stream_Element_Offset;
1229 Flags : Request_Flag_Type := No_Request_Flag);
1230 -- Receive message from Socket. Last is the index value such that Item
1231 -- (Last) is the last character assigned. Note that Last is set to
1232 -- Item'First - 1 when the socket has been closed by peer. This is not
1233 -- an error, and no exception is raised in this case unless Item'First
1234 -- is Stream_Element_Offset'First, in which case Constraint_Error is
1235 -- raised. Flags allows control of the reception. Raise Socket_Error on
1236 -- error.
1238 procedure Receive_Socket
1239 (Socket : Socket_Type;
1240 Item : out Ada.Streams.Stream_Element_Array;
1241 Last : out Ada.Streams.Stream_Element_Offset;
1242 From : out Sock_Addr_Type;
1243 Flags : Request_Flag_Type := No_Request_Flag);
1244 -- Receive message from Socket. If Socket is not connection-oriented, the
1245 -- source address From of the message is filled in. Last is the index
1246 -- value such that Item (Last) is the last character assigned. Flags
1247 -- allows control of the reception. Raises Socket_Error on error.
1249 procedure Receive_Vector
1250 (Socket : Socket_Type;
1251 Vector : Vector_Type;
1252 Count : out Ada.Streams.Stream_Element_Count;
1253 Flags : Request_Flag_Type := No_Request_Flag);
1254 -- Receive data from a socket and scatter it into the set of vector
1255 -- elements Vector. Count is set to the count of received stream elements.
1256 -- Flags allow control over reception.
1258 function Resolve_Exception
1259 (Occurrence : Ada.Exceptions.Exception_Occurrence) return Error_Type;
1260 -- When Socket_Error or Host_Error are raised, the exception message
1261 -- contains the error code between brackets and a string describing the
1262 -- error code. Resolve_Error extracts the error code from an exception
1263 -- message and translate it into an enumeration value.
1265 procedure Send_Socket
1266 (Socket : Socket_Type;
1267 Item : Ada.Streams.Stream_Element_Array;
1268 Last : out Ada.Streams.Stream_Element_Offset;
1269 To : access Sock_Addr_Type;
1270 Flags : Request_Flag_Type := No_Request_Flag);
1271 pragma Inline (Send_Socket);
1272 -- Transmit a message over a socket. For a datagram socket, the address
1273 -- is given by To.all. For a stream socket, To must be null. Last
1274 -- is the index value such that Item (Last) is the last character
1275 -- sent. Note that Last is set to Item'First - 1 if the socket has been
1276 -- closed by the peer (unless Item'First is Stream_Element_Offset'First,
1277 -- in which case Constraint_Error is raised instead). This is not an error,
1278 -- and Socket_Error is not raised in that case. Flags allows control of the
1279 -- transmission. Raises exception Socket_Error on error. Note: this
1280 -- subprogram is inlined because it is also used to implement the two
1281 -- variants below.
1283 procedure Send_Socket
1284 (Socket : Socket_Type;
1285 Item : Ada.Streams.Stream_Element_Array;
1286 Last : out Ada.Streams.Stream_Element_Offset;
1287 Flags : Request_Flag_Type := No_Request_Flag);
1288 -- Transmit a message over a socket. Upon return, Last is set to the index
1289 -- within Item of the last element transmitted. Flags allows control of
1290 -- the transmission. Raises Socket_Error on any detected error condition.
1292 procedure Send_Socket
1293 (Socket : Socket_Type;
1294 Item : Ada.Streams.Stream_Element_Array;
1295 Last : out Ada.Streams.Stream_Element_Offset;
1296 To : Sock_Addr_Type;
1297 Flags : Request_Flag_Type := No_Request_Flag);
1298 -- Transmit a message over a datagram socket. The destination address is
1299 -- To. Flags allows control of the transmission. Raises Socket_Error on
1300 -- error.
1302 procedure Send_Vector
1303 (Socket : Socket_Type;
1304 Vector : Vector_Type;
1305 Count : out Ada.Streams.Stream_Element_Count;
1306 Flags : Request_Flag_Type := No_Request_Flag);
1307 -- Transmit data gathered from the set of vector elements Vector to a
1308 -- socket. Count is set to the count of transmitted stream elements. Flags
1309 -- allow control over transmission.
1311 procedure Set_Close_On_Exec
1312 (Socket : Socket_Type;
1313 Close_On_Exec : Boolean;
1314 Status : out Boolean);
1315 -- When Close_On_Exec is True, mark Socket to be closed automatically when
1316 -- a new program is executed by the calling process (i.e. prevent Socket
1317 -- from being inherited by child processes). When Close_On_Exec is False,
1318 -- mark Socket to not be closed on exec (i.e. allow it to be inherited).
1319 -- Status is False if the operation could not be performed, or is not
1320 -- supported on the target platform.
1322 procedure Set_Socket_Option
1323 (Socket : Socket_Type;
1324 Level : Level_Type;
1325 Option : Option_Type);
1326 -- Manipulate socket options. Raises Socket_Error on error
1328 procedure Shutdown_Socket
1329 (Socket : Socket_Type;
1330 How : Shutmode_Type := Shut_Read_Write);
1331 -- Shutdown a connected socket. If How is Shut_Read further receives will
1332 -- be disallowed. If How is Shut_Write further sends will be disallowed.
1333 -- If How is Shut_Read_Write further sends and receives will be disallowed.
1335 type Stream_Access is access all Ada.Streams.Root_Stream_Type'Class;
1336 -- Same interface as Ada.Streams.Stream_IO
1338 function Stream (Socket : Socket_Type) return Stream_Access;
1339 -- Create a stream associated with a connected stream-based socket.
1340 -- Note: keep in mind that the default stream attributes for composite
1341 -- types perform separate Read/Write operations for each component,
1342 -- recursively. If performance is an issue, you may want to consider
1343 -- introducing a buffering stage.
1345 function Stream
1346 (Socket : Socket_Type;
1347 Send_To : Sock_Addr_Type) return Stream_Access;
1348 -- Create a stream associated with an already bound datagram-based socket.
1349 -- Send_To is the destination address to which messages are being sent.
1351 function Get_Address
1352 (Stream : not null Stream_Access) return Sock_Addr_Type;
1353 -- Return the socket address from which the last message was received
1355 procedure Free is new Ada.Unchecked_Deallocation
1356 (Ada.Streams.Root_Stream_Type'Class, Stream_Access);
1357 -- Destroy a stream created by one of the Stream functions above, releasing
1358 -- the corresponding resources. The user is responsible for calling this
1359 -- subprogram when the stream is not needed anymore.
1361 type Socket_Set_Type is limited private;
1362 -- This type allows manipulation of sets of sockets. It allows waiting
1363 -- for events on multiple endpoints at one time. This type has default
1364 -- initialization, and the default value is the empty set.
1366 -- Note: This type used to contain a pointer to dynamically allocated
1367 -- storage, but this is not the case anymore, and no special precautions
1368 -- are required to avoid memory leaks.
1370 procedure Clear (Item : in out Socket_Set_Type; Socket : Socket_Type);
1371 -- Remove Socket from Item
1373 procedure Copy (Source : Socket_Set_Type; Target : out Socket_Set_Type);
1374 -- Copy Source into Target as Socket_Set_Type is limited private
1376 procedure Empty (Item : out Socket_Set_Type);
1377 -- Remove all Sockets from Item
1379 procedure Get (Item : in out Socket_Set_Type; Socket : out Socket_Type);
1380 -- Extract a Socket from socket set Item. Socket is set to
1381 -- No_Socket when the set is empty.
1383 function Is_Empty (Item : Socket_Set_Type) return Boolean;
1384 -- Return True iff Item is empty
1386 function Is_Set
1387 (Item : Socket_Set_Type;
1388 Socket : Socket_Type) return Boolean;
1389 -- Return True iff Socket is present in Item
1391 procedure Set (Item : in out Socket_Set_Type; Socket : Socket_Type);
1392 -- Insert Socket into Item
1394 function Image (Item : Socket_Set_Type) return String;
1395 -- Return a printable image of Item, for debugging purposes
1397 -- The select(2) system call waits for events to occur on any of a set of
1398 -- file descriptors. Usually, three independent sets of descriptors are
1399 -- watched (read, write and exception). A timeout gives an upper bound
1400 -- on the amount of time elapsed before select returns. This function
1401 -- blocks until an event occurs. On some platforms, the select(2) system
1402 -- can block the full process (not just the calling thread).
1404 -- Check_Selector provides the very same behavior. The only difference is
1405 -- that it does not watch for exception events. Note that on some platforms
1406 -- it is kept process blocking on purpose. The timeout parameter allows the
1407 -- user to have the behavior he wants. Abort_Selector allows the safe
1408 -- abort of a blocked Check_Selector call. A special socket is opened by
1409 -- Create_Selector and included in each call to Check_Selector.
1411 -- Abort_Selector causes an event to occur on this descriptor in order to
1412 -- unblock Check_Selector. Note that each call to Abort_Selector will cause
1413 -- exactly one call to Check_Selector to return with Aborted status. The
1414 -- special socket created by Create_Selector is closed when Close_Selector
1415 -- is called.
1417 -- A typical case where it is useful to abort a Check_Selector operation is
1418 -- the situation where a change to the monitored sockets set must be made.
1420 procedure Create_Selector (Selector : out Selector_Type);
1421 -- Initialize (open) a new selector
1423 procedure Close_Selector (Selector : in out Selector_Type);
1424 -- Close Selector and all internal descriptors associated; deallocate any
1425 -- associated resources. This subprogram may be called only when there is
1426 -- no other task still using Selector (i.e. still executing Check_Selector
1427 -- or Abort_Selector on this Selector). Has no effect if Selector is
1428 -- already closed.
1430 procedure Check_Selector
1431 (Selector : Selector_Type;
1432 R_Socket_Set : in out Socket_Set_Type;
1433 W_Socket_Set : in out Socket_Set_Type;
1434 Status : out Selector_Status;
1435 Timeout : Selector_Duration := Forever);
1436 -- Return when one Socket in R_Socket_Set has some data to be read or if
1437 -- one Socket in W_Socket_Set is ready to transmit some data. In these
1438 -- cases Status is set to Completed and sockets that are ready are set in
1439 -- R_Socket_Set or W_Socket_Set. Status is set to Expired if no socket was
1440 -- ready after a Timeout expiration. Status is set to Aborted if an abort
1441 -- signal has been received while checking socket status.
1443 -- Note that two different Socket_Set_Type objects must be passed as
1444 -- R_Socket_Set and W_Socket_Set (even if they denote the same set of
1445 -- Sockets), or some event may be lost. Also keep in mind that this
1446 -- procedure modifies the passed socket sets to indicate which sockets
1447 -- actually had events upon return. The socket set therefore has to
1448 -- be reset by the caller for further calls.
1450 -- Socket_Error is raised when the select(2) system call returns an error
1451 -- condition, or when a read error occurs on the signalling socket used for
1452 -- the implementation of Abort_Selector.
1454 procedure Check_Selector
1455 (Selector : Selector_Type;
1456 R_Socket_Set : in out Socket_Set_Type;
1457 W_Socket_Set : in out Socket_Set_Type;
1458 E_Socket_Set : in out Socket_Set_Type;
1459 Status : out Selector_Status;
1460 Timeout : Selector_Duration := Forever);
1461 -- This refined version of Check_Selector allows watching for exception
1462 -- events (i.e. notifications of out-of-band transmission and reception).
1463 -- As above, all of R_Socket_Set, W_Socket_Set and E_Socket_Set must be
1464 -- different objects.
1466 procedure Abort_Selector (Selector : Selector_Type);
1467 -- Send an abort signal to the selector. The Selector may not be the
1468 -- Null_Selector.
1470 type Fd_Set is private;
1471 -- ??? This type must not be used directly, it needs to be visible because
1472 -- it is used in the visible part of GNAT.Sockets.Thin_Common. This is
1473 -- really an inversion of abstraction. The private part of GNAT.Sockets
1474 -- needs to have visibility on this type, but since Thin_Common is a child
1475 -- of Sockets, the type can't be declared there. The correct fix would
1476 -- be to move the thin sockets binding outside of GNAT.Sockets altogether,
1477 -- e.g. by renaming it to GNAT.Sockets_Thin.
1479 private
1481 package ASU renames Ada.Strings.Unbounded;
1483 type Socket_Type is new Integer;
1484 No_Socket : constant Socket_Type := -1;
1486 -- A selector is either a null selector, which is always "open" and can
1487 -- never be aborted, or a regular selector, which is created "closed",
1488 -- becomes "open" when Create_Selector is called, and "closed" again when
1489 -- Close_Selector is called.
1491 type Selector_Type (Is_Null : Boolean := False) is limited record
1492 case Is_Null is
1493 when True =>
1494 null;
1496 when False =>
1497 R_Sig_Socket : Socket_Type := No_Socket;
1498 W_Sig_Socket : Socket_Type := No_Socket;
1499 -- Signalling sockets used to abort a select operation
1500 end case;
1501 end record;
1503 pragma Volatile (Selector_Type);
1505 Null_Selector : constant Selector_Type := (Is_Null => True);
1507 type Fd_Set is
1508 new System.Storage_Elements.Storage_Array (1 .. SOSC.SIZEOF_fd_set);
1509 for Fd_Set'Alignment use Interfaces.C.long'Alignment;
1510 -- Set conservative alignment so that our Fd_Sets are always adequately
1511 -- aligned for the underlying data type (which is implementation defined
1512 -- and may be an array of C long integers).
1514 type Fd_Set_Access is access all Fd_Set;
1515 pragma Convention (C, Fd_Set_Access);
1516 No_Fd_Set_Access : constant Fd_Set_Access := null;
1518 type Socket_Set_Type is record
1519 Last : Socket_Type := No_Socket;
1520 -- Highest socket in set. Last = No_Socket denotes an empty set (which
1521 -- is the default initial value).
1523 Set : aliased Fd_Set;
1524 -- Underlying socket set. Note that the contents of this component is
1525 -- undefined if Last = No_Socket.
1526 end record;
1528 Any_Port : constant Port_Type := 0;
1529 No_Port : constant Port_Type := 0;
1531 Any_Inet_Addr : constant Inet_Addr_Type :=
1532 (Family_Inet, [others => 0]);
1533 Any_Inet6_Addr : constant Inet_Addr_Type :=
1534 (Family_Inet6, [others => 0]);
1535 No_Inet_Addr : constant Inet_Addr_Type :=
1536 (Family_Inet, [others => 0]);
1537 Broadcast_Inet_Addr : constant Inet_Addr_Type :=
1538 (Family_Inet, [others => 255]);
1539 Loopback_Inet_Addr : constant Inet_Addr_Type :=
1540 (Family_Inet, [127, 0, 0, 1]);
1541 Loopback_Inet6_Addr : constant Inet_Addr_Type :=
1542 (Family_Inet6,
1543 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]);
1545 Unspecified_Group_Inet_Addr : constant Inet_Addr_Type :=
1546 (Family_Inet, [224, 0, 0, 0]);
1547 All_Hosts_Group_Inet_Addr : constant Inet_Addr_Type :=
1548 (Family_Inet, [224, 0, 0, 1]);
1549 All_Routers_Group_Inet_Addr : constant Inet_Addr_Type :=
1550 (Family_Inet, [224, 0, 0, 2]);
1552 Unspecified_Group_Inet6_Addr : constant Inet_Addr_Type :=
1553 (Family_Inet6, [255, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
1554 All_Hosts_Group_Inet6_Addr : constant Inet_Addr_Type :=
1555 (Family_Inet6, [255, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]);
1556 All_Routers_Group_Inet6_Addr : constant Inet_Addr_Type :=
1557 (Family_Inet6, [255, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2]);
1559 No_Sock_Addr : constant Sock_Addr_Type := (Family_Inet, No_Inet_Addr, 0);
1561 Max_Name_Length : constant := SOSC.NI_MAXHOST;
1562 -- Most systems don't provide constants that specify the maximum size
1563 -- of either a FQDN or a service name. In order to aid applications in
1564 -- allocating buffers, the constant NI_MAXHOST is defined in <netdb.h>.
1566 subtype Name_Index is Natural range 1 .. Max_Name_Length;
1568 type Name_Type (Length : Name_Index := Max_Name_Length) is record
1569 Name : String (1 .. Length);
1570 end record;
1571 -- We need fixed strings to avoid access types in host entry type
1573 type Name_Array is array (Positive range <>) of Name_Type;
1574 type Inet_Addr_Array is array (Positive range <>) of Inet_Addr_Type;
1576 type Host_Entry_Type (Aliases_Length, Addresses_Length : Natural) is record
1577 Official : Name_Type;
1578 Aliases : Name_Array (1 .. Aliases_Length);
1579 Addresses : Inet_Addr_Array (1 .. Addresses_Length);
1580 end record;
1582 type Service_Entry_Type (Aliases_Length : Natural) is record
1583 Official : Name_Type;
1584 Port : Port_Type;
1585 Protocol : Name_Type;
1586 Aliases : Name_Array (1 .. Aliases_Length);
1587 end record;
1589 type Request_Flag_Type is mod 2 ** 8;
1590 No_Request_Flag : constant Request_Flag_Type := 0;
1591 Process_Out_Of_Band_Data : constant Request_Flag_Type := 1;
1592 Peek_At_Incoming_Data : constant Request_Flag_Type := 2;
1593 Wait_For_A_Full_Reception : constant Request_Flag_Type := 4;
1594 Send_End_Of_Record : constant Request_Flag_Type := 8;
1596 procedure Raise_Socket_Error (Error : Integer) with No_Return;
1597 -- Raise Socket_Error with an exception message describing the error code
1598 -- from errno.
1600 end GNAT.Sockets;