1 ------------------------------------------------------------------------------
3 -- GNAT COMPILER COMPONENTS --
5 -- G N A T . S O C K E T S --
9 -- Copyright (C) 2001-2011, AdaCore --
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. --
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. --
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/>. --
27 -- GNAT was originally developed by the GNAT team at New York University. --
28 -- Extensive contributions were provided by Ada Core Technologies Inc. --
30 ------------------------------------------------------------------------------
32 -- This package provides an interface to the sockets communication facility
33 -- provided on many operating systems. This is implemented on the following
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
42 -- The VMS implementation was implemented using the DECC RTL Socket API,
43 -- and is thus subject to limitations in the implementation of this API.
45 -- VxWorks cross ports fully implement this package
47 -- This package is not yet implemented on LynxOS or other cross ports
51 with Ada.Unchecked_Deallocation;
55 with System.OS_Constants;
56 with System.Storage_Elements;
58 package GNAT.Sockets is
60 -- Sockets are designed to provide a consistent communication facility
61 -- between applications. This package provides an Ada binding to the
62 -- de-facto standard BSD sockets API. The documentation below covers
63 -- only the specific binding provided by this package. It assumes that
64 -- the reader is already familiar with general network programming and
65 -- sockets usage. A useful reference on this matter is W. Richard Stevens'
66 -- "UNIX Network Programming: The Sockets Networking API"
67 -- (ISBN: 0131411551).
69 -- GNAT.Sockets has been designed with several ideas in mind
71 -- This is a system independent interface. Therefore, we try as much as
72 -- possible to mask system incompatibilities. Some functionalities are not
73 -- available because there are not fully supported on some systems.
75 -- This is a thick binding. For instance, a major effort has been done to
76 -- avoid using memory addresses or untyped ints. We preferred to define
77 -- streams and enumeration types. Errors are not returned as returned
78 -- values but as exceptions.
80 -- This package provides a POSIX-compliant interface (between two
81 -- different implementations of the same routine, we adopt the one closest
82 -- to the POSIX specification). For instance, using select(), the
83 -- notification of an asynchronous connect failure is delivered in the
84 -- write socket set (POSIX) instead of the exception socket set (NT).
86 -- The example below demonstrates various features of GNAT.Sockets:
88 -- with GNAT.Sockets; use GNAT.Sockets;
91 -- with Ada.Exceptions; use Ada.Exceptions;
93 -- procedure PingPong is
95 -- Group : constant String := "239.255.128.128";
96 -- -- Multicast group: administratively scoped IP address
104 -- Address : Sock_Addr_Type;
105 -- Server : Socket_Type;
106 -- Socket : Socket_Type;
107 -- Channel : Stream_Access;
112 -- -- Get an Internet address of a host (here the local host name).
113 -- -- Note that a host can have several addresses. Here we get
114 -- -- the first one which is supposed to be the official one.
116 -- Address.Addr := Addresses (Get_Host_By_Name (Host_Name), 1);
118 -- -- Get a socket address that is an Internet address and a port
120 -- Address.Port := 5876;
122 -- -- The first step is to create a socket. Once created, this
123 -- -- socket must be associated to with an address. Usually only a
124 -- -- server (Pong here) needs to bind an address explicitly. Most
125 -- -- of the time clients can skip this step because the socket
126 -- -- routines will bind an arbitrary address to an unbound socket.
128 -- Create_Socket (Server);
130 -- -- Allow reuse of local addresses
135 -- (Reuse_Address, True));
137 -- Bind_Socket (Server, Address);
139 -- -- A server marks a socket as willing to receive connect events
141 -- Listen_Socket (Server);
143 -- -- Once a server calls Listen_Socket, incoming connects events
144 -- -- can be accepted. The returned Socket is a new socket that
145 -- -- represents the server side of the connection. Server remains
146 -- -- available to receive further connections.
148 -- Accept_Socket (Server, Socket, Address);
150 -- -- Return a stream associated to the connected socket
152 -- Channel := Stream (Socket);
154 -- -- Force Pong to block
158 -- -- Receive and print message from client Ping
161 -- Message : String := String'Input (Channel);
164 -- Ada.Text_IO.Put_Line (Message);
166 -- -- Send same message back to client Ping
168 -- String'Output (Channel, Message);
171 -- Close_Socket (Server);
172 -- Close_Socket (Socket);
174 -- -- Part of the multicast example
176 -- -- Create a datagram socket to send connectionless, unreliable
177 -- -- messages of a fixed maximum length.
179 -- Create_Socket (Socket, Family_Inet, Socket_Datagram);
181 -- -- Allow reuse of local addresses
186 -- (Reuse_Address, True));
188 -- -- Controls the live time of the datagram to avoid it being
189 -- -- looped forever due to routing errors. Routers decrement
190 -- -- the TTL of every datagram as it traverses from one network
191 -- -- to another and when its value reaches 0 the packet is
192 -- -- dropped. Default is 1.
196 -- IP_Protocol_For_IP_Level,
197 -- (Multicast_TTL, 1));
199 -- -- Want the data you send to be looped back to your host
203 -- IP_Protocol_For_IP_Level,
204 -- (Multicast_Loop, True));
206 -- -- If this socket is intended to receive messages, bind it
207 -- -- to a given socket address.
209 -- Address.Addr := Any_Inet_Addr;
210 -- Address.Port := 55505;
212 -- Bind_Socket (Socket, Address);
214 -- -- Join a multicast group
216 -- -- Portability note: On Windows, this option may be set only
217 -- -- on a bound socket.
221 -- IP_Protocol_For_IP_Level,
222 -- (Add_Membership, Inet_Addr (Group), Any_Inet_Addr));
224 -- -- If this socket is intended to send messages, provide the
225 -- -- receiver socket address.
227 -- Address.Addr := Inet_Addr (Group);
228 -- Address.Port := 55506;
230 -- Channel := Stream (Socket, Address);
232 -- -- Receive and print message from client Ping
235 -- Message : String := String'Input (Channel);
238 -- -- Get the address of the sender
240 -- Address := Get_Address (Channel);
241 -- Ada.Text_IO.Put_Line (Message & " from " & Image (Address));
243 -- -- Send same message back to client Ping
245 -- String'Output (Channel, Message);
248 -- Close_Socket (Socket);
252 -- exception when E : others =>
253 -- Ada.Text_IO.Put_Line
254 -- (Exception_Name (E) & ": " & Exception_Message (E));
263 -- Address : Sock_Addr_Type;
264 -- Socket : Socket_Type;
265 -- Channel : Stream_Access;
270 -- -- See comments in Ping section for the first steps
272 -- Address.Addr := Addresses (Get_Host_By_Name (Host_Name), 1);
273 -- Address.Port := 5876;
274 -- Create_Socket (Socket);
279 -- (Reuse_Address, True));
281 -- -- Force Pong to block
285 -- -- If the client's socket is not bound, Connect_Socket will
286 -- -- bind to an unused address. The client uses Connect_Socket to
287 -- -- create a logical connection between the client's socket and
288 -- -- a server's socket returned by Accept_Socket.
290 -- Connect_Socket (Socket, Address);
292 -- Channel := Stream (Socket);
294 -- -- Send message to server Pong
296 -- String'Output (Channel, "Hello world");
298 -- -- Force Ping to block
302 -- -- Receive and print message from server Pong
304 -- Ada.Text_IO.Put_Line (String'Input (Channel));
305 -- Close_Socket (Socket);
307 -- -- Part of multicast example. Code similar to Pong's one
309 -- Create_Socket (Socket, Family_Inet, Socket_Datagram);
314 -- (Reuse_Address, True));
318 -- IP_Protocol_For_IP_Level,
319 -- (Multicast_TTL, 1));
323 -- IP_Protocol_For_IP_Level,
324 -- (Multicast_Loop, True));
326 -- Address.Addr := Any_Inet_Addr;
327 -- Address.Port := 55506;
329 -- Bind_Socket (Socket, Address);
333 -- IP_Protocol_For_IP_Level,
334 -- (Add_Membership, Inet_Addr (Group), Any_Inet_Addr));
336 -- Address.Addr := Inet_Addr (Group);
337 -- Address.Port := 55505;
339 -- Channel := Stream (Socket, Address);
341 -- -- Send message to server Pong
343 -- String'Output (Channel, "Hello world");
345 -- -- Receive and print message from server Pong
348 -- Message : String := String'Input (Channel);
351 -- Address := Get_Address (Channel);
352 -- Ada.Text_IO.Put_Line (Message & " from " & Image (Address));
355 -- Close_Socket (Socket);
359 -- exception when E : others =>
360 -- Ada.Text_IO.Put_Line
361 -- (Exception_Name (E) & ": " & Exception_Message (E));
373 package SOSC renames System.OS_Constants;
374 -- Renaming used to provide short-hand notations throughout the sockets
375 -- binding. Note that System.OS_Constants is an internal unit, and the
376 -- entities declared therein are not meant for direct access by users,
377 -- including through this renaming.
379 procedure Initialize;
381 (Entity => Initialize,
382 Message => "explicit initialization is no longer required");
383 -- Initialize must be called before using any other socket routines.
384 -- Note that this operation is a no-op on UNIX platforms, but applications
385 -- should make sure to call it if portability is expected: some platforms
386 -- (such as Windows) require initialization before any socket operation.
387 -- This is now a no-op (initialization and finalization are done
390 procedure Initialize (Process_Blocking_IO : Boolean);
392 (Entity => Initialize,
393 Message => "passing a parameter to Initialize is no longer supported");
394 -- Previous versions of GNAT.Sockets used to require the user to indicate
395 -- whether socket I/O was process- or thread-blocking on the platform.
396 -- This property is now determined automatically when the run-time library
397 -- is built. The old version of Initialize, taking a parameter, is kept
398 -- for compatibility reasons, but this interface is obsolete (and if the
399 -- value given is wrong, an exception will be raised at run time).
400 -- This is now a no-op (initialization and finalization are done
406 Message => "explicit finalization is no longer required");
407 -- After Finalize is called it is not possible to use any routines
408 -- exported in by this package. This procedure is idempotent.
409 -- This is now a no-op (initialization and finalization are done
412 type Socket_Type is private;
413 -- Sockets are used to implement a reliable bi-directional point-to-point,
414 -- stream-based connections between hosts. No_Socket provides a special
415 -- value to denote uninitialized sockets.
417 No_Socket : constant Socket_Type;
419 type Selector_Type is limited private;
420 type Selector_Access is access all Selector_Type;
421 -- Selector objects are used to wait for i/o events to occur on sockets
423 Null_Selector : constant Selector_Type;
424 -- The Null_Selector can be used in place of a normal selector without
425 -- having to call Create_Selector if the use of Abort_Selector is not
428 -- Timeval_Duration is a subtype of Standard.Duration because the full
429 -- range of Standard.Duration cannot be represented in the equivalent C
430 -- structure. Moreover, negative values are not allowed to avoid system
431 -- incompatibilities.
433 Immediate : constant Duration := 0.0;
435 Timeval_Forever : constant := 1.0 * SOSC.MAX_tv_sec;
436 Forever : constant Duration :=
437 Duration'Min (Duration'Last, Timeval_Forever);
438 subtype Timeval_Duration is Duration range Immediate .. Forever;
439 -- These needs commenting, in particular we should explain what these is
440 -- used for, and how the Timeval_Forever value is chosen (see r176463) ???
442 subtype Selector_Duration is Timeval_Duration;
443 -- Timeout value for selector operations
445 type Selector_Status is (Completed, Expired, Aborted);
446 -- Completion status of a selector operation, indicated as follows:
447 -- Complete: one of the expected events occurred
448 -- Expired: no event occurred before the expiration of the timeout
449 -- Aborted: an external action cancelled the wait operation before
450 -- any event occurred.
452 Socket_Error : exception;
453 -- There is only one exception in this package to deal with an error during
454 -- a socket routine. Once raised, its message contains a string describing
457 function Image (Socket : Socket_Type) return String;
458 -- Return a printable string for Socket
460 function To_C (Socket : Socket_Type) return Integer;
461 -- Return a file descriptor to be used by external subprograms. This is
462 -- useful for C functions that are not yet interfaced in this package.
464 type Family_Type is (Family_Inet, Family_Inet6);
465 -- Address family (or protocol family) identifies the communication domain
466 -- and groups protocols with similar address formats.
468 type Mode_Type is (Socket_Stream, Socket_Datagram);
469 -- Stream sockets provide connection-oriented byte streams. Datagram
470 -- sockets support unreliable connectionless message based communication.
472 type Shutmode_Type is (Shut_Read, Shut_Write, Shut_Read_Write);
473 -- When a process closes a socket, the policy is to retain any data queued
474 -- until either a delivery or a timeout expiration (in this case, the data
475 -- are discarded). A finer control is available through shutdown. With
476 -- Shut_Read, no more data can be received from the socket. With_Write, no
477 -- more data can be transmitted. Neither transmission nor reception can be
478 -- performed with Shut_Read_Write.
480 type Port_Type is range 0 .. 16#ffff#;
481 -- TCP/UDP port number
483 Any_Port : constant Port_Type;
486 No_Port : constant Port_Type;
487 -- Uninitialized port number
489 type Inet_Addr_Type (Family : Family_Type := Family_Inet) is private;
490 -- An Internet address depends on an address family (IPv4 contains 4 octets
491 -- and IPv6 contains 16 octets). Any_Inet_Addr is a special value treated
492 -- like a wildcard enabling all addresses. No_Inet_Addr provides a special
493 -- value to denote uninitialized inet addresses.
495 Any_Inet_Addr : constant Inet_Addr_Type;
496 No_Inet_Addr : constant Inet_Addr_Type;
497 Broadcast_Inet_Addr : constant Inet_Addr_Type;
498 Loopback_Inet_Addr : constant Inet_Addr_Type;
500 -- Useful constants for IPv4 multicast addresses
502 Unspecified_Group_Inet_Addr : constant Inet_Addr_Type;
503 All_Hosts_Group_Inet_Addr : constant Inet_Addr_Type;
504 All_Routers_Group_Inet_Addr : constant Inet_Addr_Type;
506 type Sock_Addr_Type (Family : Family_Type := Family_Inet) is record
507 Addr : Inet_Addr_Type (Family);
510 -- Socket addresses fully define a socket connection with protocol family,
511 -- an Internet address and a port. No_Sock_Addr provides a special value
512 -- for uninitialized socket addresses.
514 No_Sock_Addr : constant Sock_Addr_Type;
516 function Image (Value : Inet_Addr_Type) return String;
517 -- Return an image of an Internet address. IPv4 notation consists in 4
518 -- octets in decimal format separated by dots. IPv6 notation consists in
519 -- 16 octets in hexadecimal format separated by colons (and possibly
522 function Image (Value : Sock_Addr_Type) return String;
523 -- Return inet address image and port image separated by a colon
525 function Inet_Addr (Image : String) return Inet_Addr_Type;
526 -- Convert address image from numbers-and-dots notation into an
529 -- Host entries provide complete information on a given host: the official
530 -- name, an array of alternative names or aliases and array of network
534 (Aliases_Length, Addresses_Length : Natural) is private;
536 function Official_Name (E : Host_Entry_Type) return String;
537 -- Return official name in host entry
539 function Aliases_Length (E : Host_Entry_Type) return Natural;
540 -- Return number of aliases in host entry
542 function Addresses_Length (E : Host_Entry_Type) return Natural;
543 -- Return number of addresses in host entry
546 (E : Host_Entry_Type;
547 N : Positive := 1) return String;
548 -- Return N'th aliases in host entry. The first index is 1
551 (E : Host_Entry_Type;
552 N : Positive := 1) return Inet_Addr_Type;
553 -- Return N'th addresses in host entry. The first index is 1
555 Host_Error : exception;
556 -- Exception raised by the two following procedures. Once raised, its
557 -- message contains a string describing the error code. This exception is
558 -- raised when an host entry cannot be retrieved.
560 function Get_Host_By_Address
561 (Address : Inet_Addr_Type;
562 Family : Family_Type := Family_Inet) return Host_Entry_Type;
563 -- Return host entry structure for the given Inet address. Note that no
564 -- result will be returned if there is no mapping of this IP address to a
565 -- host name in the system tables (host database, DNS or otherwise).
567 function Get_Host_By_Name
568 (Name : String) return Host_Entry_Type;
569 -- Return host entry structure for the given host name. Here name is
570 -- either a host name, or an IP address. If Name is an IP address, this
571 -- is equivalent to Get_Host_By_Address (Inet_Addr (Name)).
573 function Host_Name return String;
574 -- Return the name of the current host
576 type Service_Entry_Type (Aliases_Length : Natural) is private;
577 -- Service entries provide complete information on a given service: the
578 -- official name, an array of alternative names or aliases and the port
581 function Official_Name (S : Service_Entry_Type) return String;
582 -- Return official name in service entry
584 function Port_Number (S : Service_Entry_Type) return Port_Type;
585 -- Return port number in service entry
587 function Protocol_Name (S : Service_Entry_Type) return String;
588 -- Return Protocol in service entry (usually UDP or TCP)
590 function Aliases_Length (S : Service_Entry_Type) return Natural;
591 -- Return number of aliases in service entry
594 (S : Service_Entry_Type;
595 N : Positive := 1) return String;
596 -- Return N'th aliases in service entry (the first index is 1)
598 function Get_Service_By_Name
600 Protocol : String) return Service_Entry_Type;
601 -- Return service entry structure for the given service name
603 function Get_Service_By_Port
605 Protocol : String) return Service_Entry_Type;
606 -- Return service entry structure for the given service port number
608 Service_Error : exception;
609 -- Comment required ???
611 -- Errors are described by an enumeration type. There is only one exception
612 -- Socket_Error in this package to deal with an error during a socket
613 -- routine. Once raised, its message contains the error code between
614 -- brackets and a string describing the error code.
616 -- The name of the enumeration constant documents the error condition
617 -- Note that on some platforms, a single error value is used for both
618 -- EWOULDBLOCK and EAGAIN. Both errors are therefore always reported as
619 -- Resource_Temporarily_Unavailable.
624 Address_Already_In_Use,
625 Cannot_Assign_Requested_Address,
626 Address_Family_Not_Supported_By_Protocol,
627 Operation_Already_In_Progress,
629 Software_Caused_Connection_Abort,
631 Connection_Reset_By_Peer,
632 Destination_Address_Required,
636 Operation_Now_In_Progress,
637 Interrupted_System_Call,
640 Transport_Endpoint_Already_Connected,
641 Too_Many_Symbolic_Links,
646 Network_Dropped_Connection_Because_Of_Reset,
647 Network_Is_Unreachable,
648 No_Buffer_Space_Available,
649 Protocol_Not_Available,
650 Transport_Endpoint_Not_Connected,
651 Socket_Operation_On_Non_Socket,
652 Operation_Not_Supported,
653 Protocol_Family_Not_Supported,
654 Protocol_Not_Supported,
655 Protocol_Wrong_Type_For_Socket,
656 Cannot_Send_After_Transport_Endpoint_Shutdown,
657 Socket_Type_Not_Supported,
658 Connection_Timed_Out,
660 Resource_Temporarily_Unavailable,
663 Host_Name_Lookup_Failure,
664 Non_Recoverable_Error,
665 Unknown_Server_Error,
666 Cannot_Resolve_Error);
668 -- Get_Socket_Options and Set_Socket_Options manipulate options associated
669 -- with a socket. Options may exist at multiple protocol levels in the
670 -- communication stack. Socket_Level is the uppermost socket level.
674 IP_Protocol_For_IP_Level,
675 IP_Protocol_For_UDP_Level,
676 IP_Protocol_For_TCP_Level);
678 -- There are several options available to manipulate sockets. Each option
679 -- has a name and several values available. Most of the time, the value is
680 -- a boolean to enable or disable this option.
683 (Keep_Alive, -- Enable sending of keep-alive messages
684 Reuse_Address, -- Allow bind to reuse local address
685 Broadcast, -- Enable datagram sockets to recv/send broadcasts
686 Send_Buffer, -- Set/get the maximum socket send buffer in bytes
687 Receive_Buffer, -- Set/get the maximum socket recv buffer in bytes
688 Linger, -- Shutdown wait for msg to be sent or timeout occur
689 Error, -- Get and clear the pending socket error
690 No_Delay, -- Do not delay send to coalesce data (TCP_NODELAY)
691 Add_Membership, -- Join a multicast group
692 Drop_Membership, -- Leave a multicast group
693 Multicast_If, -- Set default out interface for multicast packets
694 Multicast_TTL, -- Set the time-to-live of sent multicast packets
695 Multicast_Loop, -- Sent multicast packets are looped to local socket
696 Receive_Packet_Info, -- Receive low level packet info as ancillary data
697 Send_Timeout, -- Set timeout value for output
698 Receive_Timeout); -- Set timeout value for input
700 type Option_Type (Name : Option_Name := Keep_Alive) is record
707 Receive_Packet_Info |
725 when Add_Membership |
727 Multicast_Address : Inet_Addr_Type;
728 Local_Interface : Inet_Addr_Type;
731 Outgoing_If : Inet_Addr_Type;
733 when Multicast_TTL =>
734 Time_To_Live : Natural;
738 Timeout : Timeval_Duration;
743 -- There are several controls available to manipulate sockets. Each option
744 -- has a name and several values available. These controls differ from the
745 -- socket options in that they are not specific to sockets but are
746 -- available for any device.
749 (Non_Blocking_IO, -- Cause a caller not to wait on blocking operations
750 N_Bytes_To_Read); -- Return the number of bytes available to read
752 type Request_Type (Name : Request_Name := Non_Blocking_IO) is record
754 when Non_Blocking_IO =>
757 when N_Bytes_To_Read =>
763 -- A request flag allows to specify the type of message transmissions or
764 -- receptions. A request flag can be combination of zero or more
765 -- predefined request flags.
767 type Request_Flag_Type is private;
769 No_Request_Flag : constant Request_Flag_Type;
770 -- This flag corresponds to the normal execution of an operation
772 Process_Out_Of_Band_Data : constant Request_Flag_Type;
773 -- This flag requests that the receive or send function operates on
774 -- out-of-band data when the socket supports this notion (e.g.
777 Peek_At_Incoming_Data : constant Request_Flag_Type;
778 -- This flag causes the receive operation to return data from the beginning
779 -- of the receive queue without removing that data from the queue. A
780 -- subsequent receive call will return the same data.
782 Wait_For_A_Full_Reception : constant Request_Flag_Type;
783 -- This flag requests that the operation block until the full request is
784 -- satisfied. However, the call may still return less data than requested
785 -- if a signal is caught, an error or disconnect occurs, or the next data
786 -- to be received is of a different type than that returned. Note that
787 -- this flag depends on support in the underlying sockets implementation,
788 -- and is not supported under Windows.
790 Send_End_Of_Record : constant Request_Flag_Type;
791 -- This flag indicates that the entire message has been sent and so this
792 -- terminates the record.
794 function "+" (L, R : Request_Flag_Type) return Request_Flag_Type;
795 -- Combine flag L with flag R
797 type Stream_Element_Reference is access all Ada.Streams.Stream_Element;
799 type Vector_Element is record
800 Base : Stream_Element_Reference;
801 Length : Ada.Streams.Stream_Element_Count;
804 type Vector_Type is array (Integer range <>) of Vector_Element;
806 procedure Create_Socket
807 (Socket : out Socket_Type;
808 Family : Family_Type := Family_Inet;
809 Mode : Mode_Type := Socket_Stream);
810 -- Create an endpoint for communication. Raises Socket_Error on error
812 procedure Accept_Socket
813 (Server : Socket_Type;
814 Socket : out Socket_Type;
815 Address : out Sock_Addr_Type);
816 -- Extracts the first connection request on the queue of pending
817 -- connections, creates a new connected socket with mostly the same
818 -- properties as Server, and allocates a new socket. The returned Address
819 -- is filled in with the address of the connection. Raises Socket_Error on
822 procedure Accept_Socket
823 (Server : Socket_Type;
824 Socket : out Socket_Type;
825 Address : out Sock_Addr_Type;
826 Timeout : Selector_Duration;
827 Selector : access Selector_Type := null;
828 Status : out Selector_Status);
829 -- Accept a new connection on Server using Accept_Socket, waiting no longer
830 -- than the given timeout duration. Status is set to indicate whether the
831 -- operation completed successfully, timed out, or was aborted. If Selector
832 -- is not null, the designated selector is used to wait for the socket to
833 -- become available, else a private selector object is created by this
834 -- procedure and destroyed before it returns.
836 procedure Bind_Socket
837 (Socket : Socket_Type;
838 Address : Sock_Addr_Type);
839 -- Once a socket is created, assign a local address to it. Raise
840 -- Socket_Error on error.
842 procedure Close_Socket (Socket : Socket_Type);
843 -- Close a socket and more specifically a non-connected socket
845 procedure Connect_Socket
846 (Socket : Socket_Type;
847 Server : Sock_Addr_Type);
848 -- Make a connection to another socket which has the address of Server.
849 -- Raises Socket_Error on error.
851 procedure Connect_Socket
852 (Socket : Socket_Type;
853 Server : Sock_Addr_Type;
854 Timeout : Selector_Duration;
855 Selector : access Selector_Type := null;
856 Status : out Selector_Status);
857 -- Connect Socket to the given Server address using Connect_Socket, waiting
858 -- no longer than the given timeout duration. Status is set to indicate
859 -- whether the operation completed successfully, timed out, or was aborted.
860 -- If Selector is not null, the designated selector is used to wait for the
861 -- socket to become available, else a private selector object is created
862 -- by this procedure and destroyed before it returns.
864 procedure Control_Socket
865 (Socket : Socket_Type;
866 Request : in out Request_Type);
867 -- Obtain or set parameter values that control the socket. This control
868 -- differs from the socket options in that they are not specific to sockets
869 -- but are available for any device.
871 function Get_Peer_Name (Socket : Socket_Type) return Sock_Addr_Type;
872 -- Return the peer or remote socket address of a socket. Raise
873 -- Socket_Error on error.
875 function Get_Socket_Name (Socket : Socket_Type) return Sock_Addr_Type;
876 -- Return the local or current socket address of a socket. Return
877 -- No_Sock_Addr on error (e.g. socket closed or not locally bound).
879 function Get_Socket_Option
880 (Socket : Socket_Type;
881 Level : Level_Type := Socket_Level;
882 Name : Option_Name) return Option_Type;
883 -- Get the options associated with a socket. Raises Socket_Error on error
885 procedure Listen_Socket
886 (Socket : Socket_Type;
887 Length : Natural := 15);
888 -- To accept connections, a socket is first created with Create_Socket,
889 -- a willingness to accept incoming connections and a queue Length for
890 -- incoming connections are specified. Raise Socket_Error on error.
891 -- The queue length of 15 is an example value that should be appropriate
892 -- in usual cases. It can be adjusted according to each application's
893 -- particular requirements.
895 procedure Receive_Socket
896 (Socket : Socket_Type;
897 Item : out Ada.Streams.Stream_Element_Array;
898 Last : out Ada.Streams.Stream_Element_Offset;
899 Flags : Request_Flag_Type := No_Request_Flag);
900 -- Receive message from Socket. Last is the index value such that Item
901 -- (Last) is the last character assigned. Note that Last is set to
902 -- Item'First - 1 when the socket has been closed by peer. This is not
903 -- an error, and no exception is raised in this case unless Item'First
904 -- is Stream_Element_Offset'First, in which case Constraint_Error is
905 -- raised. Flags allows to control the reception. Raise Socket_Error on
908 procedure Receive_Socket
909 (Socket : Socket_Type;
910 Item : out Ada.Streams.Stream_Element_Array;
911 Last : out Ada.Streams.Stream_Element_Offset;
912 From : out Sock_Addr_Type;
913 Flags : Request_Flag_Type := No_Request_Flag);
914 -- Receive message from Socket. If Socket is not connection-oriented, the
915 -- source address From of the message is filled in. Last is the index
916 -- value such that Item (Last) is the last character assigned. Flags
917 -- allows to control the reception. Raises Socket_Error on error.
919 procedure Receive_Vector
920 (Socket : Socket_Type;
921 Vector : Vector_Type;
922 Count : out Ada.Streams.Stream_Element_Count;
923 Flags : Request_Flag_Type := No_Request_Flag);
924 -- Receive data from a socket and scatter it into the set of vector
925 -- elements Vector. Count is set to the count of received stream elements.
926 -- Flags allow control over reception.
928 function Resolve_Exception
929 (Occurrence : Ada.Exceptions.Exception_Occurrence) return Error_Type;
930 -- When Socket_Error or Host_Error are raised, the exception message
931 -- contains the error code between brackets and a string describing the
932 -- error code. Resolve_Error extracts the error code from an exception
933 -- message and translate it into an enumeration value.
935 procedure Send_Socket
936 (Socket : Socket_Type;
937 Item : Ada.Streams.Stream_Element_Array;
938 Last : out Ada.Streams.Stream_Element_Offset;
939 To : access Sock_Addr_Type;
940 Flags : Request_Flag_Type := No_Request_Flag);
941 pragma Inline (Send_Socket);
942 -- Transmit a message over a socket. For a datagram socket, the address
943 -- is given by To.all. For a stream socket, To must be null. Last
944 -- is the index value such that Item (Last) is the last character
945 -- sent. Note that Last is set to Item'First - 1 if the socket has been
946 -- closed by the peer (unless Item'First is Stream_Element_Offset'First,
947 -- in which case Constraint_Error is raised instead). This is not an error,
948 -- and Socket_Error is not raised in that case. Flags allows control of the
949 -- transmission. Raises exception Socket_Error on error. Note: this
950 -- subprogram is inlined because it is also used to implement the two
953 procedure Send_Socket
954 (Socket : Socket_Type;
955 Item : Ada.Streams.Stream_Element_Array;
956 Last : out Ada.Streams.Stream_Element_Offset;
957 Flags : Request_Flag_Type := No_Request_Flag);
958 -- Transmit a message over a socket. Upon return, Last is set to the index
959 -- within Item of the last element transmitted. Flags allows to control
960 -- the transmission. Raises Socket_Error on any detected error condition.
962 procedure Send_Socket
963 (Socket : Socket_Type;
964 Item : Ada.Streams.Stream_Element_Array;
965 Last : out Ada.Streams.Stream_Element_Offset;
967 Flags : Request_Flag_Type := No_Request_Flag);
968 -- Transmit a message over a datagram socket. The destination address is
969 -- To. Flags allows to control the transmission. Raises Socket_Error on
972 procedure Send_Vector
973 (Socket : Socket_Type;
974 Vector : Vector_Type;
975 Count : out Ada.Streams.Stream_Element_Count;
976 Flags : Request_Flag_Type := No_Request_Flag);
977 -- Transmit data gathered from the set of vector elements Vector to a
978 -- socket. Count is set to the count of transmitted stream elements. Flags
979 -- allow control over transmission.
981 procedure Set_Socket_Option
982 (Socket : Socket_Type;
983 Level : Level_Type := Socket_Level;
984 Option : Option_Type);
985 -- Manipulate socket options. Raises Socket_Error on error
987 procedure Shutdown_Socket
988 (Socket : Socket_Type;
989 How : Shutmode_Type := Shut_Read_Write);
990 -- Shutdown a connected socket. If How is Shut_Read further receives will
991 -- be disallowed. If How is Shut_Write further sends will be disallowed.
992 -- If How is Shut_Read_Write further sends and receives will be disallowed.
994 type Stream_Access is access all Ada.Streams.Root_Stream_Type'Class;
995 -- Same interface as Ada.Streams.Stream_IO
997 function Stream (Socket : Socket_Type) return Stream_Access;
998 -- Create a stream associated with an already connected stream-based socket
1001 (Socket : Socket_Type;
1002 Send_To : Sock_Addr_Type) return Stream_Access;
1003 -- Create a stream associated with an already bound datagram-based socket.
1004 -- Send_To is the destination address to which messages are being sent.
1006 function Get_Address
1007 (Stream : not null Stream_Access) return Sock_Addr_Type;
1008 -- Return the socket address from which the last message was received
1010 procedure Free is new Ada.Unchecked_Deallocation
1011 (Ada.Streams.Root_Stream_Type'Class, Stream_Access);
1012 -- Destroy a stream created by one of the Stream functions above, releasing
1013 -- the corresponding resources. The user is responsible for calling this
1014 -- subprogram when the stream is not needed anymore.
1016 type Socket_Set_Type is limited private;
1017 -- This type allows to manipulate sets of sockets. It allows to wait for
1018 -- events on multiple endpoints at one time. This type has default
1019 -- initialization, and the default value is the empty set.
1021 -- Note: This type used to contain a pointer to dynamically allocated
1022 -- storage, but this is not the case anymore, and no special precautions
1023 -- are required to avoid memory leaks.
1025 procedure Clear (Item : in out Socket_Set_Type; Socket : Socket_Type);
1026 -- Remove Socket from Item
1028 procedure Copy (Source : Socket_Set_Type; Target : out Socket_Set_Type);
1029 -- Copy Source into Target as Socket_Set_Type is limited private
1031 procedure Empty (Item : out Socket_Set_Type);
1032 -- Remove all Sockets from Item
1034 procedure Get (Item : in out Socket_Set_Type; Socket : out Socket_Type);
1035 -- Extract a Socket from socket set Item. Socket is set to
1036 -- No_Socket when the set is empty.
1038 function Is_Empty (Item : Socket_Set_Type) return Boolean;
1039 -- Return True iff Item is empty
1042 (Item : Socket_Set_Type;
1043 Socket : Socket_Type) return Boolean;
1044 -- Return True iff Socket is present in Item
1046 procedure Set (Item : in out Socket_Set_Type; Socket : Socket_Type);
1047 -- Insert Socket into Item
1049 function Image (Item : Socket_Set_Type) return String;
1050 -- Return a printable image of Item, for debugging purposes
1052 -- The select(2) system call waits for events to occur on any of a set of
1053 -- file descriptors. Usually, three independent sets of descriptors are
1054 -- watched (read, write and exception). A timeout gives an upper bound
1055 -- on the amount of time elapsed before select returns. This function
1056 -- blocks until an event occurs. On some platforms, the select(2) system
1057 -- can block the full process (not just the calling thread).
1059 -- Check_Selector provides the very same behaviour. The only difference is
1060 -- that it does not watch for exception events. Note that on some platforms
1061 -- it is kept process blocking on purpose. The timeout parameter allows the
1062 -- user to have the behaviour he wants. Abort_Selector allows to safely
1063 -- abort a blocked Check_Selector call. A special socket is opened by
1064 -- Create_Selector and included in each call to Check_Selector.
1066 -- Abort_Selector causes an event to occur on this descriptor in order to
1067 -- unblock Check_Selector. Note that each call to Abort_Selector will cause
1068 -- exactly one call to Check_Selector to return with Aborted status. The
1069 -- special socket created by Create_Selector is closed when Close_Selector
1072 -- A typical case where it is useful to abort a Check_Selector operation is
1073 -- the situation where a change to the monitored sockets set must be made.
1075 procedure Create_Selector (Selector : out Selector_Type);
1076 -- Initialize (open) a new selector
1078 procedure Close_Selector (Selector : in out Selector_Type);
1079 -- Close Selector and all internal descriptors associated; deallocate any
1080 -- associated resources. This subprogram may be called only when there is
1081 -- no other task still using Selector (i.e. still executing Check_Selector
1082 -- or Abort_Selector on this Selector). Has no effect if Selector is
1085 procedure Check_Selector
1086 (Selector : Selector_Type;
1087 R_Socket_Set : in out Socket_Set_Type;
1088 W_Socket_Set : in out Socket_Set_Type;
1089 Status : out Selector_Status;
1090 Timeout : Selector_Duration := Forever);
1091 -- Return when one Socket in R_Socket_Set has some data to be read or if
1092 -- one Socket in W_Socket_Set is ready to transmit some data. In these
1093 -- cases Status is set to Completed and sockets that are ready are set in
1094 -- R_Socket_Set or W_Socket_Set. Status is set to Expired if no socket was
1095 -- ready after a Timeout expiration. Status is set to Aborted if an abort
1096 -- signal has been received while checking socket status.
1098 -- Note that two different Socket_Set_Type objects must be passed as
1099 -- R_Socket_Set and W_Socket_Set (even if they denote the same set of
1100 -- Sockets), or some event may be lost.
1102 -- Socket_Error is raised when the select(2) system call returns an error
1103 -- condition, or when a read error occurs on the signalling socket used for
1104 -- the implementation of Abort_Selector.
1106 procedure Check_Selector
1107 (Selector : Selector_Type;
1108 R_Socket_Set : in out Socket_Set_Type;
1109 W_Socket_Set : in out Socket_Set_Type;
1110 E_Socket_Set : in out Socket_Set_Type;
1111 Status : out Selector_Status;
1112 Timeout : Selector_Duration := Forever);
1113 -- This refined version of Check_Selector allows watching for exception
1114 -- events (i.e. notifications of out-of-band transmission and reception).
1115 -- As above, all of R_Socket_Set, W_Socket_Set and E_Socket_Set must be
1116 -- different objects.
1118 procedure Abort_Selector (Selector : Selector_Type);
1119 -- Send an abort signal to the selector. The Selector may not be the
1122 type Fd_Set is private;
1123 -- ??? This type must not be used directly, it needs to be visible because
1124 -- it is used in the visible part of GNAT.Sockets.Thin_Common. This is
1125 -- really an inversion of abstraction. The private part of GNAT.Sockets
1126 -- needs to have visibility on this type, but since Thin_Common is a child
1127 -- of Sockets, the type can't be declared there. The correct fix would
1128 -- be to move the thin sockets binding outside of GNAT.Sockets altogether,
1129 -- e.g. by renaming it to GNAT.Sockets_Thin.
1133 type Socket_Type is new Integer;
1134 No_Socket : constant Socket_Type := -1;
1136 -- A selector is either a null selector, which is always "open" and can
1137 -- never be aborted, or a regular selector, which is created "closed",
1138 -- becomes "open" when Create_Selector is called, and "closed" again when
1139 -- Close_Selector is called.
1141 type Selector_Type (Is_Null : Boolean := False) is limited record
1147 R_Sig_Socket : Socket_Type := No_Socket;
1148 W_Sig_Socket : Socket_Type := No_Socket;
1149 -- Signalling sockets used to abort a select operation
1154 pragma Volatile (Selector_Type);
1156 Null_Selector : constant Selector_Type := (Is_Null => True);
1159 new System.Storage_Elements.Storage_Array (1 .. SOSC.SIZEOF_fd_set);
1160 for Fd_Set'Alignment use Interfaces.C.long'Alignment;
1161 -- Set conservative alignment so that our Fd_Sets are always adequately
1162 -- aligned for the underlying data type (which is implementation defined
1163 -- and may be an array of C long integers).
1165 type Fd_Set_Access is access all Fd_Set;
1166 pragma Convention (C, Fd_Set_Access);
1167 No_Fd_Set_Access : constant Fd_Set_Access := null;
1169 type Socket_Set_Type is record
1170 Last : Socket_Type := No_Socket;
1171 -- Highest socket in set. Last = No_Socket denotes an empty set (which
1172 -- is the default initial value).
1174 Set : aliased Fd_Set;
1175 -- Underlying socket set. Note that the contents of this component is
1176 -- undefined if Last = No_Socket.
1179 subtype Inet_Addr_Comp_Type is Natural range 0 .. 255;
1180 -- Octet for Internet address
1182 type Inet_Addr_VN_Type is array (Natural range <>) of Inet_Addr_Comp_Type;
1184 subtype Inet_Addr_V4_Type is Inet_Addr_VN_Type (1 .. 4);
1185 subtype Inet_Addr_V6_Type is Inet_Addr_VN_Type (1 .. 16);
1187 type Inet_Addr_Type (Family : Family_Type := Family_Inet) is record
1190 Sin_V4 : Inet_Addr_V4_Type := (others => 0);
1192 when Family_Inet6 =>
1193 Sin_V6 : Inet_Addr_V6_Type := (others => 0);
1197 Any_Port : constant Port_Type := 0;
1198 No_Port : constant Port_Type := 0;
1200 Any_Inet_Addr : constant Inet_Addr_Type :=
1201 (Family_Inet, (others => 0));
1202 No_Inet_Addr : constant Inet_Addr_Type :=
1203 (Family_Inet, (others => 0));
1204 Broadcast_Inet_Addr : constant Inet_Addr_Type :=
1205 (Family_Inet, (others => 255));
1206 Loopback_Inet_Addr : constant Inet_Addr_Type :=
1207 (Family_Inet, (127, 0, 0, 1));
1209 Unspecified_Group_Inet_Addr : constant Inet_Addr_Type :=
1210 (Family_Inet, (224, 0, 0, 0));
1211 All_Hosts_Group_Inet_Addr : constant Inet_Addr_Type :=
1212 (Family_Inet, (224, 0, 0, 1));
1213 All_Routers_Group_Inet_Addr : constant Inet_Addr_Type :=
1214 (Family_Inet, (224, 0, 0, 2));
1216 No_Sock_Addr : constant Sock_Addr_Type := (Family_Inet, No_Inet_Addr, 0);
1218 Max_Name_Length : constant := 64;
1219 -- The constant MAXHOSTNAMELEN is usually set to 64
1221 subtype Name_Index is Natural range 1 .. Max_Name_Length;
1223 type Name_Type (Length : Name_Index := Max_Name_Length) is record
1224 Name : String (1 .. Length);
1226 -- We need fixed strings to avoid access types in host entry type
1228 type Name_Array is array (Natural range <>) of Name_Type;
1229 type Inet_Addr_Array is array (Natural range <>) of Inet_Addr_Type;
1231 type Host_Entry_Type (Aliases_Length, Addresses_Length : Natural) is record
1232 Official : Name_Type;
1233 Aliases : Name_Array (1 .. Aliases_Length);
1234 Addresses : Inet_Addr_Array (1 .. Addresses_Length);
1237 type Service_Entry_Type (Aliases_Length : Natural) is record
1238 Official : Name_Type;
1239 Aliases : Name_Array (1 .. Aliases_Length);
1241 Protocol : Name_Type;
1244 type Request_Flag_Type is mod 2 ** 8;
1245 No_Request_Flag : constant Request_Flag_Type := 0;
1246 Process_Out_Of_Band_Data : constant Request_Flag_Type := 1;
1247 Peek_At_Incoming_Data : constant Request_Flag_Type := 2;
1248 Wait_For_A_Full_Reception : constant Request_Flag_Type := 4;
1249 Send_End_Of_Record : constant Request_Flag_Type := 8;