2010-12-20 Tobias Burnus <burnus@net-b.de>
[official-gcc.git] / gcc / ada / g-socket.ads
blob169538a4d754a45f668f60fdb6d9560a6e5422ec
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-2010, 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 2, 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. See the GNU General Public License --
17 -- for more details. You should have received a copy of the GNU General --
18 -- Public License distributed with GNAT; see file COPYING. If not, write --
19 -- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, --
20 -- Boston, MA 02110-1301, USA. --
21 -- --
22 -- As a special exception, if other files instantiate generics from this --
23 -- unit, or you link this unit with other files to produce an executable, --
24 -- this unit does not by itself cause the resulting executable to be --
25 -- covered by the GNU General Public License. This exception does not --
26 -- however invalidate any other reasons why the executable file might be --
27 -- covered by the GNU Public License. --
28 -- --
29 -- GNAT was originally developed by the GNAT team at New York University. --
30 -- Extensive contributions were provided by Ada Core Technologies Inc. --
31 -- --
32 ------------------------------------------------------------------------------
34 -- This package provides an interface to the sockets communication facility
35 -- provided on many operating systems. This is implemented on the following
36 -- platforms:
38 -- All native ports, with restrictions as follows
40 -- Multicast is available only on systems which provide support for this
41 -- feature, so it is not available if Multicast is not supported, or not
42 -- installed.
44 -- The VMS implementation was implemented using the DECC RTL Socket API,
45 -- and is thus subject to limitations in the implementation of this API.
47 -- VxWorks cross ports fully implement this package
49 -- This package is not yet implemented on LynxOS or other cross ports
51 with Ada.Exceptions;
52 with Ada.Streams;
53 with Ada.Unchecked_Deallocation;
55 with Interfaces.C;
57 with System.OS_Constants;
58 with System.Storage_Elements;
60 package GNAT.Sockets is
62 -- Sockets are designed to provide a consistent communication facility
63 -- between applications. This package provides an Ada binding to the
64 -- de-facto standard BSD sockets API. The documentation below covers
65 -- only the specific binding provided by this package. It assumes that
66 -- the reader is already familiar with general network programming and
67 -- sockets usage. A useful reference on this matter is W. Richard Stevens'
68 -- "UNIX Network Programming: The Sockets Networking API"
69 -- (ISBN: 0131411551).
71 -- GNAT.Sockets has been designed with several ideas in mind
73 -- This is a system independent interface. Therefore, we try as much as
74 -- possible to mask system incompatibilities. Some functionalities are not
75 -- available because there are not fully supported on some systems.
77 -- This is a thick binding. For instance, a major effort has been done to
78 -- avoid using memory addresses or untyped ints. We preferred to define
79 -- streams and enumeration types. Errors are not returned as returned
80 -- values but as exceptions.
82 -- This package provides a POSIX-compliant interface (between two
83 -- different implementations of the same routine, we adopt the one closest
84 -- to the POSIX specification). For instance, using select(), the
85 -- notification of an asynchronous connect failure is delivered in the
86 -- write socket set (POSIX) instead of the exception socket set (NT).
88 -- The example below demonstrates various features of GNAT.Sockets:
90 -- with GNAT.Sockets; use GNAT.Sockets;
92 -- with Ada.Text_IO;
93 -- with Ada.Exceptions; use Ada.Exceptions;
95 -- procedure PingPong is
97 -- Group : constant String := "239.255.128.128";
98 -- -- Multicast group: administratively scoped IP address
100 -- task Pong is
101 -- entry Start;
102 -- entry Stop;
103 -- end Pong;
105 -- task body Pong is
106 -- Address : Sock_Addr_Type;
107 -- Server : Socket_Type;
108 -- Socket : Socket_Type;
109 -- Channel : Stream_Access;
111 -- begin
112 -- accept Start;
114 -- -- Get an Internet address of a host (here the local host name).
115 -- -- Note that a host can have several addresses. Here we get
116 -- -- the first one which is supposed to be the official one.
118 -- Address.Addr := Addresses (Get_Host_By_Name (Host_Name), 1);
120 -- -- Get a socket address that is an Internet address and a port
122 -- Address.Port := 5876;
124 -- -- The first step is to create a socket. Once created, this
125 -- -- socket must be associated to with an address. Usually only a
126 -- -- server (Pong here) needs to bind an address explicitly. Most
127 -- -- of the time clients can skip this step because the socket
128 -- -- routines will bind an arbitrary address to an unbound socket.
130 -- Create_Socket (Server);
132 -- -- Allow reuse of local addresses
134 -- Set_Socket_Option
135 -- (Server,
136 -- Socket_Level,
137 -- (Reuse_Address, True));
139 -- Bind_Socket (Server, Address);
141 -- -- A server marks a socket as willing to receive connect events
143 -- Listen_Socket (Server);
145 -- -- Once a server calls Listen_Socket, incoming connects events
146 -- -- can be accepted. The returned Socket is a new socket that
147 -- -- represents the server side of the connection. Server remains
148 -- -- available to receive further connections.
150 -- Accept_Socket (Server, Socket, Address);
152 -- -- Return a stream associated to the connected socket
154 -- Channel := Stream (Socket);
156 -- -- Force Pong to block
158 -- delay 0.2;
160 -- -- Receive and print message from client Ping
162 -- declare
163 -- Message : String := String'Input (Channel);
165 -- begin
166 -- Ada.Text_IO.Put_Line (Message);
168 -- -- Send same message back to client Ping
170 -- String'Output (Channel, Message);
171 -- end;
173 -- Close_Socket (Server);
174 -- Close_Socket (Socket);
176 -- -- Part of the multicast example
178 -- -- Create a datagram socket to send connectionless, unreliable
179 -- -- messages of a fixed maximum length.
181 -- Create_Socket (Socket, Family_Inet, Socket_Datagram);
183 -- -- Allow reuse of local addresses
185 -- Set_Socket_Option
186 -- (Socket,
187 -- Socket_Level,
188 -- (Reuse_Address, True));
190 -- -- Controls the live time of the datagram to avoid it being
191 -- -- looped forever due to routing errors. Routers decrement
192 -- -- the TTL of every datagram as it traverses from one network
193 -- -- to another and when its value reaches 0 the packet is
194 -- -- dropped. Default is 1.
196 -- Set_Socket_Option
197 -- (Socket,
198 -- IP_Protocol_For_IP_Level,
199 -- (Multicast_TTL, 1));
201 -- -- Want the data you send to be looped back to your host
203 -- Set_Socket_Option
204 -- (Socket,
205 -- IP_Protocol_For_IP_Level,
206 -- (Multicast_Loop, True));
208 -- -- If this socket is intended to receive messages, bind it
209 -- -- to a given socket address.
211 -- Address.Addr := Any_Inet_Addr;
212 -- Address.Port := 55505;
214 -- Bind_Socket (Socket, Address);
216 -- -- Join a multicast group
218 -- -- Portability note: On Windows, this option may be set only
219 -- -- on a bound socket.
221 -- Set_Socket_Option
222 -- (Socket,
223 -- IP_Protocol_For_IP_Level,
224 -- (Add_Membership, Inet_Addr (Group), Any_Inet_Addr));
226 -- -- If this socket is intended to send messages, provide the
227 -- -- receiver socket address.
229 -- Address.Addr := Inet_Addr (Group);
230 -- Address.Port := 55506;
232 -- Channel := Stream (Socket, Address);
234 -- -- Receive and print message from client Ping
236 -- declare
237 -- Message : String := String'Input (Channel);
239 -- begin
240 -- -- Get the address of the sender
242 -- Address := Get_Address (Channel);
243 -- Ada.Text_IO.Put_Line (Message & " from " & Image (Address));
245 -- -- Send same message back to client Ping
247 -- String'Output (Channel, Message);
248 -- end;
250 -- Close_Socket (Socket);
252 -- accept Stop;
254 -- exception when E : others =>
255 -- Ada.Text_IO.Put_Line
256 -- (Exception_Name (E) & ": " & Exception_Message (E));
257 -- end Pong;
259 -- task Ping is
260 -- entry Start;
261 -- entry Stop;
262 -- end Ping;
264 -- task body Ping is
265 -- Address : Sock_Addr_Type;
266 -- Socket : Socket_Type;
267 -- Channel : Stream_Access;
269 -- begin
270 -- accept Start;
272 -- -- See comments in Ping section for the first steps
274 -- Address.Addr := Addresses (Get_Host_By_Name (Host_Name), 1);
275 -- Address.Port := 5876;
276 -- Create_Socket (Socket);
278 -- Set_Socket_Option
279 -- (Socket,
280 -- Socket_Level,
281 -- (Reuse_Address, True));
283 -- -- Force Pong to block
285 -- delay 0.2;
287 -- -- If the client's socket is not bound, Connect_Socket will
288 -- -- bind to an unused address. The client uses Connect_Socket to
289 -- -- create a logical connection between the client's socket and
290 -- -- a server's socket returned by Accept_Socket.
292 -- Connect_Socket (Socket, Address);
294 -- Channel := Stream (Socket);
296 -- -- Send message to server Pong
298 -- String'Output (Channel, "Hello world");
300 -- -- Force Ping to block
302 -- delay 0.2;
304 -- -- Receive and print message from server Pong
306 -- Ada.Text_IO.Put_Line (String'Input (Channel));
307 -- Close_Socket (Socket);
309 -- -- Part of multicast example. Code similar to Pong's one
311 -- Create_Socket (Socket, Family_Inet, Socket_Datagram);
313 -- Set_Socket_Option
314 -- (Socket,
315 -- Socket_Level,
316 -- (Reuse_Address, True));
318 -- Set_Socket_Option
319 -- (Socket,
320 -- IP_Protocol_For_IP_Level,
321 -- (Multicast_TTL, 1));
323 -- Set_Socket_Option
324 -- (Socket,
325 -- IP_Protocol_For_IP_Level,
326 -- (Multicast_Loop, True));
328 -- Address.Addr := Any_Inet_Addr;
329 -- Address.Port := 55506;
331 -- Bind_Socket (Socket, Address);
333 -- Set_Socket_Option
334 -- (Socket,
335 -- IP_Protocol_For_IP_Level,
336 -- (Add_Membership, Inet_Addr (Group), Any_Inet_Addr));
338 -- Address.Addr := Inet_Addr (Group);
339 -- Address.Port := 55505;
341 -- Channel := Stream (Socket, Address);
343 -- -- Send message to server Pong
345 -- String'Output (Channel, "Hello world");
347 -- -- Receive and print message from server Pong
349 -- declare
350 -- Message : String := String'Input (Channel);
352 -- begin
353 -- Address := Get_Address (Channel);
354 -- Ada.Text_IO.Put_Line (Message & " from " & Image (Address));
355 -- end;
357 -- Close_Socket (Socket);
359 -- accept Stop;
361 -- exception when E : others =>
362 -- Ada.Text_IO.Put_Line
363 -- (Exception_Name (E) & ": " & Exception_Message (E));
364 -- end Ping;
366 -- begin
367 -- Initialize;
368 -- Ping.Start;
369 -- Pong.Start;
370 -- Ping.Stop;
371 -- Pong.Stop;
372 -- Finalize;
373 -- end PingPong;
375 package SOSC renames System.OS_Constants;
376 -- Renaming used to provide short-hand notations throughout the sockets
377 -- binding. Note that System.OS_Constants is an internal unit, and the
378 -- entities declared therein are not meant for direct access by users,
379 -- including through this renaming.
381 procedure Initialize;
382 pragma Obsolescent
383 (Entity => Initialize,
384 Message => "explicit initialization is no longer required");
385 -- Initialize must be called before using any other socket routines.
386 -- Note that this operation is a no-op on UNIX platforms, but applications
387 -- should make sure to call it if portability is expected: some platforms
388 -- (such as Windows) require initialization before any socket operation.
389 -- This is now a no-op (initialization and finalization are done
390 -- automatically).
392 procedure Initialize (Process_Blocking_IO : Boolean);
393 pragma Obsolescent
394 (Entity => Initialize,
395 Message => "passing a parameter to Initialize is no longer supported");
396 -- Previous versions of GNAT.Sockets used to require the user to indicate
397 -- whether socket I/O was process- or thread-blocking on the platform.
398 -- This property is now determined automatically when the run-time library
399 -- is built. The old version of Initialize, taking a parameter, is kept
400 -- for compatibility reasons, but this interface is obsolete (and if the
401 -- value given is wrong, an exception will be raised at run time).
402 -- This is now a no-op (initialization and finalization are done
403 -- automatically).
405 procedure Finalize;
406 pragma Obsolescent
407 (Entity => Finalize,
408 Message => "explicit finalization is no longer required");
409 -- After Finalize is called it is not possible to use any routines
410 -- exported in by this package. This procedure is idempotent.
411 -- This is now a no-op (initialization and finalization are done
412 -- automatically).
414 type Socket_Type is private;
415 -- Sockets are used to implement a reliable bi-directional point-to-point,
416 -- stream-based connections between hosts. No_Socket provides a special
417 -- value to denote uninitialized sockets.
419 No_Socket : constant Socket_Type;
421 type Selector_Type is limited private;
422 type Selector_Access is access all Selector_Type;
423 -- Selector objects are used to wait for i/o events to occur on sockets
425 Null_Selector : constant Selector_Type;
426 -- The Null_Selector can be used in place of a normal selector without
427 -- having to call Create_Selector if the use of Abort_Selector is not
428 -- required.
430 -- Timeval_Duration is a subtype of Standard.Duration because the full
431 -- range of Standard.Duration cannot be represented in the equivalent C
432 -- structure. Moreover, negative values are not allowed to avoid system
433 -- incompatibilities.
435 Immediate : constant Duration := 0.0;
437 Timeval_Forever : constant := 2.0 ** (SOSC.SIZEOF_tv_sec * 8 - 1) - 1.0;
438 Forever : constant Duration :=
439 Duration'Min (Duration'Last, Timeval_Forever);
441 subtype Timeval_Duration is Duration range Immediate .. Forever;
443 subtype Selector_Duration is Timeval_Duration;
444 -- Timeout value for selector operations
446 type Selector_Status is (Completed, Expired, Aborted);
447 -- Completion status of a selector operation, indicated as follows:
448 -- Complete: one of the expected events occurred
449 -- Expired: no event occurred before the expiration of the timeout
450 -- Aborted: an external action cancelled the wait operation before
451 -- any event occurred.
453 Socket_Error : exception;
454 -- There is only one exception in this package to deal with an error during
455 -- a socket routine. Once raised, its message contains a string describing
456 -- the error code.
458 function Image (Socket : Socket_Type) return String;
459 -- Return a printable string for Socket
461 function To_C (Socket : Socket_Type) return Integer;
462 -- Return a file descriptor to be used by external subprograms. This is
463 -- useful for C functions that are not yet interfaced in this package.
465 type Family_Type is (Family_Inet, Family_Inet6);
466 -- Address family (or protocol family) identifies the communication domain
467 -- and groups protocols with similar address formats.
469 type Mode_Type is (Socket_Stream, Socket_Datagram);
470 -- Stream sockets provide connection-oriented byte streams. Datagram
471 -- sockets support unreliable connectionless message based communication.
473 type Shutmode_Type is (Shut_Read, Shut_Write, Shut_Read_Write);
474 -- When a process closes a socket, the policy is to retain any data queued
475 -- until either a delivery or a timeout expiration (in this case, the data
476 -- are discarded). A finer control is available through shutdown. With
477 -- Shut_Read, no more data can be received from the socket. With_Write, no
478 -- more data can be transmitted. Neither transmission nor reception can be
479 -- performed with Shut_Read_Write.
481 type Port_Type is range 0 .. 16#ffff#;
482 -- TCP/UDP port number
484 Any_Port : constant Port_Type;
485 -- All ports
487 No_Port : constant Port_Type;
488 -- Uninitialized port number
490 type Inet_Addr_Type (Family : Family_Type := Family_Inet) is private;
491 -- An Internet address depends on an address family (IPv4 contains 4 octets
492 -- and IPv6 contains 16 octets). Any_Inet_Addr is a special value treated
493 -- like a wildcard enabling all addresses. No_Inet_Addr provides a special
494 -- value to denote uninitialized inet addresses.
496 Any_Inet_Addr : constant Inet_Addr_Type;
497 No_Inet_Addr : constant Inet_Addr_Type;
498 Broadcast_Inet_Addr : constant Inet_Addr_Type;
499 Loopback_Inet_Addr : constant Inet_Addr_Type;
501 -- Useful constants for IPv4 multicast addresses
503 Unspecified_Group_Inet_Addr : constant Inet_Addr_Type;
504 All_Hosts_Group_Inet_Addr : constant Inet_Addr_Type;
505 All_Routers_Group_Inet_Addr : constant Inet_Addr_Type;
507 type Sock_Addr_Type (Family : Family_Type := Family_Inet) is record
508 Addr : Inet_Addr_Type (Family);
509 Port : Port_Type;
510 end record;
511 -- Socket addresses fully define a socket connection with protocol family,
512 -- an Internet address and a port. No_Sock_Addr provides a special value
513 -- for uninitialized socket addresses.
515 No_Sock_Addr : constant Sock_Addr_Type;
517 function Image (Value : Inet_Addr_Type) return String;
518 -- Return an image of an Internet address. IPv4 notation consists in 4
519 -- octets in decimal format separated by dots. IPv6 notation consists in
520 -- 16 octets in hexadecimal format separated by colons (and possibly
521 -- dots).
523 function Image (Value : Sock_Addr_Type) return String;
524 -- Return inet address image and port image separated by a colon
526 function Inet_Addr (Image : String) return Inet_Addr_Type;
527 -- Convert address image from numbers-and-dots notation into an
528 -- inet address.
530 -- Host entries provide complete information on a given host: the official
531 -- name, an array of alternative names or aliases and array of network
532 -- addresses.
534 type Host_Entry_Type
535 (Aliases_Length, Addresses_Length : Natural) is private;
537 function Official_Name (E : Host_Entry_Type) return String;
538 -- Return official name in host entry
540 function Aliases_Length (E : Host_Entry_Type) return Natural;
541 -- Return number of aliases in host entry
543 function Addresses_Length (E : Host_Entry_Type) return Natural;
544 -- Return number of addresses in host entry
546 function Aliases
547 (E : Host_Entry_Type;
548 N : Positive := 1) return String;
549 -- Return N'th aliases in host entry. The first index is 1
551 function Addresses
552 (E : Host_Entry_Type;
553 N : Positive := 1) return Inet_Addr_Type;
554 -- Return N'th addresses in host entry. The first index is 1
556 Host_Error : exception;
557 -- Exception raised by the two following procedures. Once raised, its
558 -- message contains a string describing the error code. This exception is
559 -- raised when an host entry cannot be retrieved.
561 function Get_Host_By_Address
562 (Address : Inet_Addr_Type;
563 Family : Family_Type := Family_Inet) return Host_Entry_Type;
564 -- Return host entry structure for the given Inet address. Note that no
565 -- result will be returned if there is no mapping of this IP address to a
566 -- host name in the system tables (host database, DNS or otherwise).
568 function Get_Host_By_Name
569 (Name : String) return Host_Entry_Type;
570 -- Return host entry structure for the given host name. Here name is
571 -- either a host name, or an IP address. If Name is an IP address, this
572 -- is equivalent to Get_Host_By_Address (Inet_Addr (Name)).
574 function Host_Name return String;
575 -- Return the name of the current host
577 type Service_Entry_Type (Aliases_Length : Natural) is private;
578 -- Service entries provide complete information on a given service: the
579 -- official name, an array of alternative names or aliases and the port
580 -- number.
582 function Official_Name (S : Service_Entry_Type) return String;
583 -- Return official name in service entry
585 function Port_Number (S : Service_Entry_Type) return Port_Type;
586 -- Return port number in service entry
588 function Protocol_Name (S : Service_Entry_Type) return String;
589 -- Return Protocol in service entry (usually UDP or TCP)
591 function Aliases_Length (S : Service_Entry_Type) return Natural;
592 -- Return number of aliases in service entry
594 function Aliases
595 (S : Service_Entry_Type;
596 N : Positive := 1) return String;
597 -- Return N'th aliases in service entry (the first index is 1)
599 function Get_Service_By_Name
600 (Name : String;
601 Protocol : String) return Service_Entry_Type;
602 -- Return service entry structure for the given service name
604 function Get_Service_By_Port
605 (Port : Port_Type;
606 Protocol : String) return Service_Entry_Type;
607 -- Return service entry structure for the given service port number
609 Service_Error : exception;
610 -- Comment required ???
612 -- Errors are described by an enumeration type. There is only one exception
613 -- Socket_Error in this package to deal with an error during a socket
614 -- routine. Once raised, its message contains the error code between
615 -- brackets and a string describing the error code.
617 -- The name of the enumeration constant documents the error condition
618 -- Note that on some platforms, a single error value is used for both
619 -- EWOULDBLOCK and EAGAIN. Both errors are therefore always reported as
620 -- Resource_Temporarily_Unavailable.
622 type Error_Type is
623 (Success,
624 Permission_Denied,
625 Address_Already_In_Use,
626 Cannot_Assign_Requested_Address,
627 Address_Family_Not_Supported_By_Protocol,
628 Operation_Already_In_Progress,
629 Bad_File_Descriptor,
630 Software_Caused_Connection_Abort,
631 Connection_Refused,
632 Connection_Reset_By_Peer,
633 Destination_Address_Required,
634 Bad_Address,
635 Host_Is_Down,
636 No_Route_To_Host,
637 Operation_Now_In_Progress,
638 Interrupted_System_Call,
639 Invalid_Argument,
640 Input_Output_Error,
641 Transport_Endpoint_Already_Connected,
642 Too_Many_Symbolic_Links,
643 Too_Many_Open_Files,
644 Message_Too_Long,
645 File_Name_Too_Long,
646 Network_Is_Down,
647 Network_Dropped_Connection_Because_Of_Reset,
648 Network_Is_Unreachable,
649 No_Buffer_Space_Available,
650 Protocol_Not_Available,
651 Transport_Endpoint_Not_Connected,
652 Socket_Operation_On_Non_Socket,
653 Operation_Not_Supported,
654 Protocol_Family_Not_Supported,
655 Protocol_Not_Supported,
656 Protocol_Wrong_Type_For_Socket,
657 Cannot_Send_After_Transport_Endpoint_Shutdown,
658 Socket_Type_Not_Supported,
659 Connection_Timed_Out,
660 Too_Many_References,
661 Resource_Temporarily_Unavailable,
662 Broken_Pipe,
663 Unknown_Host,
664 Host_Name_Lookup_Failure,
665 Non_Recoverable_Error,
666 Unknown_Server_Error,
667 Cannot_Resolve_Error);
669 -- Get_Socket_Options and Set_Socket_Options manipulate options associated
670 -- with a socket. Options may exist at multiple protocol levels in the
671 -- communication stack. Socket_Level is the uppermost socket level.
673 type Level_Type is
674 (Socket_Level,
675 IP_Protocol_For_IP_Level,
676 IP_Protocol_For_UDP_Level,
677 IP_Protocol_For_TCP_Level);
679 -- There are several options available to manipulate sockets. Each option
680 -- has a name and several values available. Most of the time, the value is
681 -- a boolean to enable or disable this option.
683 type Option_Name is
684 (Keep_Alive, -- Enable sending of keep-alive messages
685 Reuse_Address, -- Allow bind to reuse local address
686 Broadcast, -- Enable datagram sockets to recv/send broadcasts
687 Send_Buffer, -- Set/get the maximum socket send buffer in bytes
688 Receive_Buffer, -- Set/get the maximum socket recv buffer in bytes
689 Linger, -- Shutdown wait for msg to be sent or timeout occur
690 Error, -- Get and clear the pending socket error
691 No_Delay, -- Do not delay send to coalesce data (TCP_NODELAY)
692 Add_Membership, -- Join a multicast group
693 Drop_Membership, -- Leave a multicast group
694 Multicast_If, -- Set default out interface for multicast packets
695 Multicast_TTL, -- Set the time-to-live of sent multicast packets
696 Multicast_Loop, -- Sent multicast packets are looped to local socket
697 Receive_Packet_Info, -- Receive low level packet info as ancillary data
698 Send_Timeout, -- Set timeout value for output
699 Receive_Timeout); -- Set timeout value for input
701 type Option_Type (Name : Option_Name := Keep_Alive) is record
702 case Name is
703 when Keep_Alive |
704 Reuse_Address |
705 Broadcast |
706 Linger |
707 No_Delay |
708 Receive_Packet_Info |
709 Multicast_Loop =>
710 Enabled : Boolean;
712 case Name is
713 when Linger =>
714 Seconds : Natural;
715 when others =>
716 null;
717 end case;
719 when Send_Buffer |
720 Receive_Buffer =>
721 Size : Natural;
723 when Error =>
724 Error : Error_Type;
726 when Add_Membership |
727 Drop_Membership =>
728 Multicast_Address : Inet_Addr_Type;
729 Local_Interface : Inet_Addr_Type;
731 when Multicast_If =>
732 Outgoing_If : Inet_Addr_Type;
734 when Multicast_TTL =>
735 Time_To_Live : Natural;
737 when Send_Timeout |
738 Receive_Timeout =>
739 Timeout : Timeval_Duration;
741 end case;
742 end record;
744 -- There are several controls available to manipulate sockets. Each option
745 -- has a name and several values available. These controls differ from the
746 -- socket options in that they are not specific to sockets but are
747 -- available for any device.
749 type Request_Name is
750 (Non_Blocking_IO, -- Cause a caller not to wait on blocking operations
751 N_Bytes_To_Read); -- Return the number of bytes available to read
753 type Request_Type (Name : Request_Name := Non_Blocking_IO) is record
754 case Name is
755 when Non_Blocking_IO =>
756 Enabled : Boolean;
758 when N_Bytes_To_Read =>
759 Size : Natural;
761 end case;
762 end record;
764 -- A request flag allows to specify the type of message transmissions or
765 -- receptions. A request flag can be combination of zero or more
766 -- predefined request flags.
768 type Request_Flag_Type is private;
770 No_Request_Flag : constant Request_Flag_Type;
771 -- This flag corresponds to the normal execution of an operation
773 Process_Out_Of_Band_Data : constant Request_Flag_Type;
774 -- This flag requests that the receive or send function operates on
775 -- out-of-band data when the socket supports this notion (e.g.
776 -- Socket_Stream).
778 Peek_At_Incoming_Data : constant Request_Flag_Type;
779 -- This flag causes the receive operation to return data from the beginning
780 -- of the receive queue without removing that data from the queue. A
781 -- subsequent receive call will return the same data.
783 Wait_For_A_Full_Reception : constant Request_Flag_Type;
784 -- This flag requests that the operation block until the full request is
785 -- satisfied. However, the call may still return less data than requested
786 -- if a signal is caught, an error or disconnect occurs, or the next data
787 -- to be received is of a different type than that returned. Note that
788 -- this flag depends on support in the underlying sockets implementation,
789 -- and is not supported under Windows.
791 Send_End_Of_Record : constant Request_Flag_Type;
792 -- This flag indicates that the entire message has been sent and so this
793 -- terminates the record.
795 function "+" (L, R : Request_Flag_Type) return Request_Flag_Type;
796 -- Combine flag L with flag R
798 type Stream_Element_Reference is access all Ada.Streams.Stream_Element;
800 type Vector_Element is record
801 Base : Stream_Element_Reference;
802 Length : Ada.Streams.Stream_Element_Count;
803 end record;
805 type Vector_Type is array (Integer range <>) of Vector_Element;
807 procedure Create_Socket
808 (Socket : out Socket_Type;
809 Family : Family_Type := Family_Inet;
810 Mode : Mode_Type := Socket_Stream);
811 -- Create an endpoint for communication. Raises Socket_Error on error
813 procedure Accept_Socket
814 (Server : Socket_Type;
815 Socket : out Socket_Type;
816 Address : out Sock_Addr_Type);
817 -- Extracts the first connection request on the queue of pending
818 -- connections, creates a new connected socket with mostly the same
819 -- properties as Server, and allocates a new socket. The returned Address
820 -- is filled in with the address of the connection. Raises Socket_Error on
821 -- error.
823 procedure Accept_Socket
824 (Server : Socket_Type;
825 Socket : out Socket_Type;
826 Address : out Sock_Addr_Type;
827 Timeout : Selector_Duration;
828 Selector : access Selector_Type := null;
829 Status : out Selector_Status);
830 -- Accept a new connection on Server using Accept_Socket, waiting no longer
831 -- than the given timeout duration. Status is set to indicate whether the
832 -- operation completed successfully, timed out, or was aborted. If Selector
833 -- is not null, the designated selector is used to wait for the socket to
834 -- become available, else a private selector object is created by this
835 -- procedure and destroyed before it returns.
837 procedure Bind_Socket
838 (Socket : Socket_Type;
839 Address : Sock_Addr_Type);
840 -- Once a socket is created, assign a local address to it. Raise
841 -- Socket_Error on error.
843 procedure Close_Socket (Socket : Socket_Type);
844 -- Close a socket and more specifically a non-connected socket
846 procedure Connect_Socket
847 (Socket : Socket_Type;
848 Server : Sock_Addr_Type);
849 -- Make a connection to another socket which has the address of Server.
850 -- Raises Socket_Error on error.
852 procedure Connect_Socket
853 (Socket : Socket_Type;
854 Server : Sock_Addr_Type;
855 Timeout : Selector_Duration;
856 Selector : access Selector_Type := null;
857 Status : out Selector_Status);
858 -- Connect Socket to the given Server address using Connect_Socket, waiting
859 -- no longer than the given timeout duration. Status is set to indicate
860 -- whether the operation completed successfully, timed out, or was aborted.
861 -- If Selector is not null, the designated selector is used to wait for the
862 -- socket to become available, else a private selector object is created
863 -- by this procedure and destroyed before it returns.
865 procedure Control_Socket
866 (Socket : Socket_Type;
867 Request : in out Request_Type);
868 -- Obtain or set parameter values that control the socket. This control
869 -- differs from the socket options in that they are not specific to sockets
870 -- but are available for any device.
872 function Get_Peer_Name (Socket : Socket_Type) return Sock_Addr_Type;
873 -- Return the peer or remote socket address of a socket. Raise
874 -- Socket_Error on error.
876 function Get_Socket_Name (Socket : Socket_Type) return Sock_Addr_Type;
877 -- Return the local or current socket address of a socket. Return
878 -- No_Sock_Addr on error (e.g. socket closed or not locally bound).
880 function Get_Socket_Option
881 (Socket : Socket_Type;
882 Level : Level_Type := Socket_Level;
883 Name : Option_Name) return Option_Type;
884 -- Get the options associated with a socket. Raises Socket_Error on error
886 procedure Listen_Socket
887 (Socket : Socket_Type;
888 Length : Natural := 15);
889 -- To accept connections, a socket is first created with Create_Socket,
890 -- a willingness to accept incoming connections and a queue Length for
891 -- incoming connections are specified. Raise Socket_Error on error.
892 -- The queue length of 15 is an example value that should be appropriate
893 -- in usual cases. It can be adjusted according to each application's
894 -- particular requirements.
896 procedure Receive_Socket
897 (Socket : Socket_Type;
898 Item : out Ada.Streams.Stream_Element_Array;
899 Last : out Ada.Streams.Stream_Element_Offset;
900 Flags : Request_Flag_Type := No_Request_Flag);
901 -- Receive message from Socket. Last is the index value such that Item
902 -- (Last) is the last character assigned. Note that Last is set to
903 -- Item'First - 1 when the socket has been closed by peer. This is not
904 -- an error, and no exception is raised in this case unless Item'First
905 -- is Stream_Element_Offset'First, in which case Constraint_Error is
906 -- raised. Flags allows to control the reception. Raise Socket_Error on
907 -- error.
909 procedure Receive_Socket
910 (Socket : Socket_Type;
911 Item : out Ada.Streams.Stream_Element_Array;
912 Last : out Ada.Streams.Stream_Element_Offset;
913 From : out Sock_Addr_Type;
914 Flags : Request_Flag_Type := No_Request_Flag);
915 -- Receive message from Socket. If Socket is not connection-oriented, the
916 -- source address From of the message is filled in. Last is the index
917 -- value such that Item (Last) is the last character assigned. Flags
918 -- allows to control the reception. Raises Socket_Error on error.
920 procedure Receive_Vector
921 (Socket : Socket_Type;
922 Vector : Vector_Type;
923 Count : out Ada.Streams.Stream_Element_Count;
924 Flags : Request_Flag_Type := No_Request_Flag);
925 -- Receive data from a socket and scatter it into the set of vector
926 -- elements Vector. Count is set to the count of received stream elements.
927 -- Flags allow control over reception.
929 function Resolve_Exception
930 (Occurrence : Ada.Exceptions.Exception_Occurrence) return Error_Type;
931 -- When Socket_Error or Host_Error are raised, the exception message
932 -- contains the error code between brackets and a string describing the
933 -- error code. Resolve_Error extracts the error code from an exception
934 -- message and translate it into an enumeration value.
936 procedure Send_Socket
937 (Socket : Socket_Type;
938 Item : Ada.Streams.Stream_Element_Array;
939 Last : out Ada.Streams.Stream_Element_Offset;
940 To : access Sock_Addr_Type;
941 Flags : Request_Flag_Type := No_Request_Flag);
942 pragma Inline (Send_Socket);
943 -- Transmit a message over a socket. For a datagram socket, the address
944 -- is given by To.all. For a stream socket, To must be null. Last
945 -- is the index value such that Item (Last) is the last character
946 -- sent. Note that Last is set to Item'First - 1 if the socket has been
947 -- closed by the peer (unless Item'First is Stream_Element_Offset'First,
948 -- in which case Constraint_Error is raised instead). This is not an error,
949 -- and Socket_Error is not raised in that case. Flags allows control of the
950 -- transmission. Raises exception Socket_Error on error. Note: this
951 -- subprogram is inlined because it is also used to implement the two
952 -- variants below.
954 procedure Send_Socket
955 (Socket : Socket_Type;
956 Item : Ada.Streams.Stream_Element_Array;
957 Last : out Ada.Streams.Stream_Element_Offset;
958 Flags : Request_Flag_Type := No_Request_Flag);
959 -- Transmit a message over a socket. Upon return, Last is set to the index
960 -- within Item of the last element transmitted. Flags allows to control
961 -- the transmission. Raises Socket_Error on any detected error condition.
963 procedure Send_Socket
964 (Socket : Socket_Type;
965 Item : Ada.Streams.Stream_Element_Array;
966 Last : out Ada.Streams.Stream_Element_Offset;
967 To : Sock_Addr_Type;
968 Flags : Request_Flag_Type := No_Request_Flag);
969 -- Transmit a message over a datagram socket. The destination address is
970 -- To. Flags allows to control the transmission. Raises Socket_Error on
971 -- error.
973 procedure Send_Vector
974 (Socket : Socket_Type;
975 Vector : Vector_Type;
976 Count : out Ada.Streams.Stream_Element_Count;
977 Flags : Request_Flag_Type := No_Request_Flag);
978 -- Transmit data gathered from the set of vector elements Vector to a
979 -- socket. Count is set to the count of transmitted stream elements. Flags
980 -- allow control over transmission.
982 procedure Set_Socket_Option
983 (Socket : Socket_Type;
984 Level : Level_Type := Socket_Level;
985 Option : Option_Type);
986 -- Manipulate socket options. Raises Socket_Error on error
988 procedure Shutdown_Socket
989 (Socket : Socket_Type;
990 How : Shutmode_Type := Shut_Read_Write);
991 -- Shutdown a connected socket. If How is Shut_Read further receives will
992 -- be disallowed. If How is Shut_Write further sends will be disallowed.
993 -- If How is Shut_Read_Write further sends and receives will be disallowed.
995 type Stream_Access is access all Ada.Streams.Root_Stream_Type'Class;
996 -- Same interface as Ada.Streams.Stream_IO
998 function Stream (Socket : Socket_Type) return Stream_Access;
999 -- Create a stream associated with an already connected stream-based socket
1001 function Stream
1002 (Socket : Socket_Type;
1003 Send_To : Sock_Addr_Type) return Stream_Access;
1004 -- Create a stream associated with an already bound datagram-based socket.
1005 -- Send_To is the destination address to which messages are being sent.
1007 function Get_Address
1008 (Stream : not null Stream_Access) return Sock_Addr_Type;
1009 -- Return the socket address from which the last message was received
1011 procedure Free is new Ada.Unchecked_Deallocation
1012 (Ada.Streams.Root_Stream_Type'Class, Stream_Access);
1013 -- Destroy a stream created by one of the Stream functions above, releasing
1014 -- the corresponding resources. The user is responsible for calling this
1015 -- subprogram when the stream is not needed anymore.
1017 type Socket_Set_Type is limited private;
1018 -- This type allows to manipulate sets of sockets. It allows to wait for
1019 -- events on multiple endpoints at one time. This type has default
1020 -- initialization, and the default value is the empty set.
1022 -- Note: This type used to contain a pointer to dynamically allocated
1023 -- storage, but this is not the case anymore, and no special precautions
1024 -- are required to avoid memory leaks.
1026 procedure Clear (Item : in out Socket_Set_Type; Socket : Socket_Type);
1027 -- Remove Socket from Item
1029 procedure Copy (Source : Socket_Set_Type; Target : out Socket_Set_Type);
1030 -- Copy Source into Target as Socket_Set_Type is limited private
1032 procedure Empty (Item : out Socket_Set_Type);
1033 -- Remove all Sockets from Item
1035 procedure Get (Item : in out Socket_Set_Type; Socket : out Socket_Type);
1036 -- Extract a Socket from socket set Item. Socket is set to
1037 -- No_Socket when the set is empty.
1039 function Is_Empty (Item : Socket_Set_Type) return Boolean;
1040 -- Return True iff Item is empty
1042 function Is_Set
1043 (Item : Socket_Set_Type;
1044 Socket : Socket_Type) return Boolean;
1045 -- Return True iff Socket is present in Item
1047 procedure Set (Item : in out Socket_Set_Type; Socket : Socket_Type);
1048 -- Insert Socket into Item
1050 function Image (Item : Socket_Set_Type) return String;
1051 -- Return a printable image of Item, for debugging purposes
1053 -- The select(2) system call waits for events to occur on any of a set of
1054 -- file descriptors. Usually, three independent sets of descriptors are
1055 -- watched (read, write and exception). A timeout gives an upper bound
1056 -- on the amount of time elapsed before select returns. This function
1057 -- blocks until an event occurs. On some platforms, the select(2) system
1058 -- can block the full process (not just the calling thread).
1060 -- Check_Selector provides the very same behaviour. The only difference is
1061 -- that it does not watch for exception events. Note that on some platforms
1062 -- it is kept process blocking on purpose. The timeout parameter allows the
1063 -- user to have the behaviour he wants. Abort_Selector allows to safely
1064 -- abort a blocked Check_Selector call. A special socket is opened by
1065 -- Create_Selector and included in each call to Check_Selector.
1067 -- Abort_Selector causes an event to occur on this descriptor in order to
1068 -- unblock Check_Selector. Note that each call to Abort_Selector will cause
1069 -- exactly one call to Check_Selector to return with Aborted status. The
1070 -- special socket created by Create_Selector is closed when Close_Selector
1071 -- is called.
1073 -- A typical case where it is useful to abort a Check_Selector operation is
1074 -- the situation where a change to the monitored sockets set must be made.
1076 procedure Create_Selector (Selector : out Selector_Type);
1077 -- Initialize (open) a new selector
1079 procedure Close_Selector (Selector : in out Selector_Type);
1080 -- Close Selector and all internal descriptors associated; deallocate any
1081 -- associated resources. This subprogram may be called only when there is
1082 -- no other task still using Selector (i.e. still executing Check_Selector
1083 -- or Abort_Selector on this Selector). Has no effect if Selector is
1084 -- already closed.
1086 procedure Check_Selector
1087 (Selector : Selector_Type;
1088 R_Socket_Set : in out Socket_Set_Type;
1089 W_Socket_Set : in out Socket_Set_Type;
1090 Status : out Selector_Status;
1091 Timeout : Selector_Duration := Forever);
1092 -- Return when one Socket in R_Socket_Set has some data to be read or if
1093 -- one Socket in W_Socket_Set is ready to transmit some data. In these
1094 -- cases Status is set to Completed and sockets that are ready are set in
1095 -- R_Socket_Set or W_Socket_Set. Status is set to Expired if no socket was
1096 -- ready after a Timeout expiration. Status is set to Aborted if an abort
1097 -- signal has been received while checking socket status.
1099 -- Note that two different Socket_Set_Type objects must be passed as
1100 -- R_Socket_Set and W_Socket_Set (even if they denote the same set of
1101 -- Sockets), or some event may be lost.
1103 -- Socket_Error is raised when the select(2) system call returns an error
1104 -- condition, or when a read error occurs on the signalling socket used for
1105 -- the implementation of Abort_Selector.
1107 procedure Check_Selector
1108 (Selector : Selector_Type;
1109 R_Socket_Set : in out Socket_Set_Type;
1110 W_Socket_Set : in out Socket_Set_Type;
1111 E_Socket_Set : in out Socket_Set_Type;
1112 Status : out Selector_Status;
1113 Timeout : Selector_Duration := Forever);
1114 -- This refined version of Check_Selector allows watching for exception
1115 -- events (i.e. notifications of out-of-band transmission and reception).
1116 -- As above, all of R_Socket_Set, W_Socket_Set and E_Socket_Set must be
1117 -- different objects.
1119 procedure Abort_Selector (Selector : Selector_Type);
1120 -- Send an abort signal to the selector. The Selector may not be the
1121 -- Null_Selector.
1123 type Fd_Set is private;
1124 -- ??? This type must not be used directly, it needs to be visible because
1125 -- it is used in the visible part of GNAT.Sockets.Thin_Common. This is
1126 -- really an inversion of abstraction. The private part of GNAT.Sockets
1127 -- needs to have visibility on this type, but since Thin_Common is a child
1128 -- of Sockets, the type can't be declared there. The correct fix would
1129 -- be to move the thin sockets binding outside of GNAT.Sockets altogether,
1130 -- e.g. by renaming it to GNAT.Sockets_Thin.
1132 private
1134 type Socket_Type is new Integer;
1135 No_Socket : constant Socket_Type := -1;
1137 -- A selector is either a null selector, which is always "open" and can
1138 -- never be aborted, or a regular selector, which is created "closed",
1139 -- becomes "open" when Create_Selector is called, and "closed" again when
1140 -- Close_Selector is called.
1142 type Selector_Type (Is_Null : Boolean := False) is limited record
1143 case Is_Null is
1144 when True =>
1145 null;
1147 when False =>
1148 R_Sig_Socket : Socket_Type := No_Socket;
1149 W_Sig_Socket : Socket_Type := No_Socket;
1150 -- Signalling sockets used to abort a select operation
1152 end case;
1153 end record;
1155 pragma Volatile (Selector_Type);
1157 Null_Selector : constant Selector_Type := (Is_Null => True);
1159 type Fd_Set is
1160 new System.Storage_Elements.Storage_Array (1 .. SOSC.SIZEOF_fd_set);
1161 for Fd_Set'Alignment use Interfaces.C.long'Alignment;
1162 -- Set conservative alignment so that our Fd_Sets are always adequately
1163 -- aligned for the underlying data type (which is implementation defined
1164 -- and may be an array of C long integers).
1166 type Fd_Set_Access is access all Fd_Set;
1167 pragma Convention (C, Fd_Set_Access);
1168 No_Fd_Set_Access : constant Fd_Set_Access := null;
1170 type Socket_Set_Type is record
1171 Last : Socket_Type := No_Socket;
1172 -- Highest socket in set. Last = No_Socket denotes an empty set (which
1173 -- is the default initial value).
1175 Set : aliased Fd_Set;
1176 -- Underlying socket set. Note that the contents of this component is
1177 -- undefined if Last = No_Socket.
1178 end record;
1180 subtype Inet_Addr_Comp_Type is Natural range 0 .. 255;
1181 -- Octet for Internet address
1183 type Inet_Addr_VN_Type is array (Natural range <>) of Inet_Addr_Comp_Type;
1185 subtype Inet_Addr_V4_Type is Inet_Addr_VN_Type (1 .. 4);
1186 subtype Inet_Addr_V6_Type is Inet_Addr_VN_Type (1 .. 16);
1188 type Inet_Addr_Type (Family : Family_Type := Family_Inet) is record
1189 case Family is
1190 when Family_Inet =>
1191 Sin_V4 : Inet_Addr_V4_Type := (others => 0);
1193 when Family_Inet6 =>
1194 Sin_V6 : Inet_Addr_V6_Type := (others => 0);
1195 end case;
1196 end record;
1198 Any_Port : constant Port_Type := 0;
1199 No_Port : constant Port_Type := 0;
1201 Any_Inet_Addr : constant Inet_Addr_Type :=
1202 (Family_Inet, (others => 0));
1203 No_Inet_Addr : constant Inet_Addr_Type :=
1204 (Family_Inet, (others => 0));
1205 Broadcast_Inet_Addr : constant Inet_Addr_Type :=
1206 (Family_Inet, (others => 255));
1207 Loopback_Inet_Addr : constant Inet_Addr_Type :=
1208 (Family_Inet, (127, 0, 0, 1));
1210 Unspecified_Group_Inet_Addr : constant Inet_Addr_Type :=
1211 (Family_Inet, (224, 0, 0, 0));
1212 All_Hosts_Group_Inet_Addr : constant Inet_Addr_Type :=
1213 (Family_Inet, (224, 0, 0, 1));
1214 All_Routers_Group_Inet_Addr : constant Inet_Addr_Type :=
1215 (Family_Inet, (224, 0, 0, 2));
1217 No_Sock_Addr : constant Sock_Addr_Type := (Family_Inet, No_Inet_Addr, 0);
1219 Max_Name_Length : constant := 64;
1220 -- The constant MAXHOSTNAMELEN is usually set to 64
1222 subtype Name_Index is Natural range 1 .. Max_Name_Length;
1224 type Name_Type (Length : Name_Index := Max_Name_Length) is record
1225 Name : String (1 .. Length);
1226 end record;
1227 -- We need fixed strings to avoid access types in host entry type
1229 type Name_Array is array (Natural range <>) of Name_Type;
1230 type Inet_Addr_Array is array (Natural range <>) of Inet_Addr_Type;
1232 type Host_Entry_Type (Aliases_Length, Addresses_Length : Natural) is record
1233 Official : Name_Type;
1234 Aliases : Name_Array (1 .. Aliases_Length);
1235 Addresses : Inet_Addr_Array (1 .. Addresses_Length);
1236 end record;
1238 type Service_Entry_Type (Aliases_Length : Natural) is record
1239 Official : Name_Type;
1240 Aliases : Name_Array (1 .. Aliases_Length);
1241 Port : Port_Type;
1242 Protocol : Name_Type;
1243 end record;
1245 type Request_Flag_Type is mod 2 ** 8;
1246 No_Request_Flag : constant Request_Flag_Type := 0;
1247 Process_Out_Of_Band_Data : constant Request_Flag_Type := 1;
1248 Peek_At_Incoming_Data : constant Request_Flag_Type := 2;
1249 Wait_For_A_Full_Reception : constant Request_Flag_Type := 4;
1250 Send_End_Of_Record : constant Request_Flag_Type := 8;
1252 end GNAT.Sockets;