1/* Part of SWI-Prolog 2 3 Author: Jan Wielemaker 4 E-mail: J.Wielemaker@vu.nl 5 WWW: http://www.swi-prolog.org 6 Copyright (c) 2000-2023, University of Amsterdam 7 VU University Amsterdam 8 CWI, Amsterdam 9 SWI-Prolog Solutions b.v. 10 All rights reserved. 11 12 Redistribution and use in source and binary forms, with or without 13 modification, are permitted provided that the following conditions 14 are met: 15 16 1. Redistributions of source code must retain the above copyright 17 notice, this list of conditions and the following disclaimer. 18 19 2. Redistributions in binary form must reproduce the above copyright 20 notice, this list of conditions and the following disclaimer in 21 the documentation and/or other materials provided with the 22 distribution. 23 24 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 25 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 26 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 27 FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 28 COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 29 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 30 BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 31 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 32 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 33 LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 34 ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 35 POSSIBILITY OF SUCH DAMAGE. 36*/ 37 38:- module(socket, 39 [ socket_create/2, % -Socket, +Options 40 tcp_socket/1, % -Socket 41 tcp_close_socket/1, % +Socket 42 tcp_open_socket/3, % +Socket, -Read, -Write 43 tcp_connect/2, % +Socket, +Address 44 tcp_connect/3, % +Address, -StreamPair, +Options 45 tcp_connect/4, % +Socket, +Address, -Read, -Write) 46 tcp_bind/2, % +Socket, +Address 47 tcp_accept/3, % +Master, -Slave, -PeerName 48 tcp_listen/2, % +Socket, +BackLog 49 tcp_fcntl/3, % +Socket, +Command, ?Arg 50 tcp_setopt/2, % +Socket, +Option 51 tcp_getopt/2, % +Socket, ?Option 52 host_address/3, % ?HostName, ?Address, +Options 53 tcp_host_to_address/2, % ?HostName, ?Ip-nr 54 tcp_select/3, % +Inputs, -Ready, +Timeout 55 gethostname/1, % -HostName 56 57 ip_name/2, % ?Ip, ?Name 58 59 tcp_open_socket/2, % +Socket, -StreamPair 60 61 udp_socket/1, % -Socket 62 udp_receive/4, % +Socket, -Data, -Sender, +Options 63 udp_send/4, % +Socket, +Data, +Sender, +Options 64 65 negotiate_socks_connection/2% +DesiredEndpoint, +StreamPair 66 ]). 67:- autoload(library(debug), [assertion/1, debug/3]). 68:- autoload(library(lists), [last/2, member/2, append/3, append/2]). 69:- autoload(library(apply), [maplist/3, maplist/2]). 70:- autoload(library(error), 71 [instantiation_error/1, syntax_error/1, must_be/2, domain_error/2]). 72:- autoload(library(option), [option/2, option/3]).
199:- multifile 200 tcp_connect_hook/3, % +Socket, +Addr, -In, -Out 201 tcp_connect_hook/4, % +Socket, +Addr, -Stream 202 proxy_for_url/3, % +URL, +Host, -ProxyList 203 try_proxy/4. % +Proxy, +Addr, -Socket, -Stream 204 205:- predicate_options(tcp_connect/3, 3, 206 [ bypass_proxy(boolean), 207 nodelay(boolean), 208 domain(oneof([inet,inet6])) 209 ]). 210 211:- use_foreign_library(foreign(socket)). 212:- public tcp_debug/1. % set debugging. 213 214:- if(current_predicate(unix_domain_socket/1)). 215:- export(unix_domain_socket/1). % -Socket 216:- endif.
inet
(default), inet6
, unix
or local
(same
as unix
)stream
(default) to create a TCP connection or
dgram
to create a UDP socket.This predicate subsumes tcp_socket/1m, udp_socket/1 and unix_domain_socket/1.
socket_create(SocketId, [])
or, explicit,
socket_create(SocketId, [domain(inet), type(stream)])
.socket_create(SocketId, [domain(unix)])
or,
explicit, socket_create(SocketId, [domain(unix), type(stream)])
Unix domain socket affect tcp_connect/2 (for clients) and
tcp_bind/2 and tcp_accept/3 (for servers). The address is an atom
or string that is handled as a file name. On most systems the
length of this file name is limited to 128 bytes (including null
terminator), but according to the Linux documentation (unix(7)
),
portable applications must keep the address below 92 bytes. Note
that these lengths are in bytes. Non-ascii characters may be
represented as multiple bytes. If the length limit is exceeded a
representation_error(af_unix_name)
exception is raised.
278tcp_open_socket(Socket, Stream) :-
279 tcp_open_socket(Socket, In, Out),
280 ( var(Out)
281 -> Stream = In
282 ; stream_pair(Stream, In, Out)
283 ).
tcp_bind(Socket, localhost:8080)
If Port is unbound, the system picks an arbitrary free port and unifies Port with the selected port number. Port is either an integer or the name of a registered service. See also tcp_connect/4.
af_unix
if Socket is an AF_UNIX socket (see
unix_domain_socket/1).tcp_socket(Socket), tcp_connect(Socket, Host:Port), tcp_open_socket(Socket, StreamPair)
Typical client applications should use the high level interface provided by tcp_connect/3 which avoids resource leaking if a step in the process fails, and can be hooked to support proxies. For example:
setup_call_cleanup( tcp_connect(Host:Port, StreamPair, []), talk(StreamPair), close(StreamPair))
If SocketId is an AF_UNIX socket (see unix_domain_socket/1), Address is an atom or string denoting a file name.
360 /******************************* 361 * HOOKABLE CONNECT * 362 *******************************/
:- multifile socket:tcp_connect_hook/4. socket:tcp_connect_hook(Socket, Address, Read, Write) :- proxy(ProxyAdress), tcp_connect(Socket, ProxyAdress), tcp_open_socket(Socket, Read, Write), proxy_connect(Address, Read, Write).
385tcp_connect(Socket, Address, Read, Write) :- 386 tcp_connect_hook(Socket, Address, Read, Write), 387 !. 388tcp_connect(Socket, Address, Read, Write) :- 389 tcp_connect(Socket, Address), 390 tcp_open_socket(Socket, Read, Write).
false
. If true
, do not attempt to use any
proxies to obtain the connectionfalse
. If true
, set nodelay on the
resulting socket using tcp_setopt(Socket, nodelay)
inet6
. When omitted we use host_address/2
with type(stream)
and try the returned addresses in order.The +,+,- mode is deprecated and does not support proxies. It behaves like tcp_connect/4, but creates a stream pair (see stream_pair/3).
431% Main mode: +,-,+ 432tcp_connect(Address, StreamPair, Options) :- 433 var(StreamPair), 434 !, 435 ( memberchk(bypass_proxy(true), Options) 436 -> tcp_connect_direct(Address, Socket, StreamPair, Options) 437 ; findall(Result, 438 try_a_proxy(Address, Result), 439 ResultList), 440 last(ResultList, Status) 441 -> ( Status = true(_Proxy, Socket, StreamPair) 442 -> true 443 ; throw(error(proxy_error(tried(ResultList)), _)) 444 ) 445 ; tcp_connect_direct(Address, Socket, StreamPair, Options) 446 ), 447 ( memberchk(nodelay(true), Options) 448 -> tcp_setopt(Socket, nodelay) 449 ; true 450 ). 451% backward compatibility mode +,+,- 452tcp_connect(Socket, Address, StreamPair) :- 453 tcp_connect_hook(Socket, Address, StreamPair0), 454 !, 455 StreamPair = StreamPair0. 456tcp_connect(Socket, Address, StreamPair) :- 457 connect_stream_pair(Socket, Address, StreamPair). 458 459:- public tcp_connect_direct/3. % used by HTTP proxy code. 460tcp_connect_direct(Address, Socket, StreamPair) :- 461 tcp_connect_direct(Address, Socket, StreamPair, []).
inet
, inet6
is
given, perform a getaddrinfo()
call to obtain the relevant
addresses.470tcp_connect_direct(Host:Port, Socket, StreamPair, Options) :- 471 \+ option(domain(_), Options), 472 !, 473 State = error(_), 474 ( host_address(Host, Address, [type(stream)]), 475 socket_create(Socket, [domain(Address.domain)]), 476 E = error(_,_), 477 catch(connect_or_discard_socket(Socket, Address.address:Port, 478 StreamPair), 479 E, store_error_and_fail(State, E)), 480 debug(socket, '~p: connected to ~p', [Host, Address.address]) 481 -> true 482 ; arg(1, State, Error), 483 assertion(nonvar(Error)), 484 throw(Error) 485 ). 486tcp_connect_direct(Address, Socket, StreamPair, Options) :- 487 make_socket(Address, Socket, Options), 488 connect_or_discard_socket(Socket, Address, StreamPair). 489 490connect_or_discard_socket(Socket, Address, StreamPair) :- 491 setup_call_catcher_cleanup( 492 true, 493 connect_stream_pair(Socket, Address, StreamPair), 494 Catcher, cleanup(Catcher, Socket)). 495 496cleanup(exit, _) :- !. 497cleanup(_, Socket) :- 498 tcp_close_socket(Socket). 499 500connect_stream_pair(Socket, Address, StreamPair) :- 501 tcp_connect(Socket, Address, Read, Write), 502 stream_pair(StreamPair, Read, Write). 503 504store_error_and_fail(State, E) :- 505 arg(1, State, E0), 506 var(E0), 507 nb_setarg(1, State, E), 508 fail. 509 510:- if(current_predicate(unix_domain_socket/1)). 511make_socket(Address, Socket, _Options) :- 512 ( atom(Address) 513 ; string(Address) 514 ), 515 !, 516 unix_domain_socket(Socket). 517:- endif. 518make_socket(_Address, Socket, Options) :- 519 option(domain(Domain), Options, inet), 520 socket_create(Socket, [domain(Domain)]).
select()
call
underlying wait_for_input/3. As input multiplexing typically happens
in a background thread anyway we accept the loss of timeouts and
interrupts.
534tcp_select(ListOfStreams, ReadyList, TimeOut) :- 535 wait_for_input(ListOfStreams, ReadyList, TimeOut). 536 537 538 /******************************* 539 * PROXY SUPPORT * 540 *******************************/ 541 542try_a_proxy(Address, Result) :- 543 format(atom(URL), 'socket://~w', [Address]), 544 ( Address = Host:_ 545 -> true 546 ; Host = Address 547 ), 548 proxy_for_url(URL, Host, Proxy), 549 debug(socket(proxy), 'Socket connecting via ~w~n', [Proxy]), 550 ( catch(try_proxy(Proxy, Address, Socket, Stream), E, true) 551 -> ( var(E) 552 -> !, Result = true(Proxy, Socket, Stream) 553 ; Result = error(Proxy, E) 554 ) 555 ; Result = false(Proxy) 556 ), 557 debug(socket(proxy), 'Socket: ~w: ~p', [Proxy, Result]).
The default implementation recognises the values for Proxy
described below. The library(http/http_proxy) adds
proxy(Host,Port)
which allows for HTTP proxies using the
CONNECT
method.
578:- multifile 579 try_proxy/4. 580 581try_proxy(direct, Address, Socket, StreamPair) :- 582 !, 583 tcp_connect_direct(Address, Socket, StreamPair). 584try_proxy(socks(Host, Port), Address, Socket, StreamPair) :- 585 !, 586 tcp_connect_direct(Host:Port, Socket, StreamPair), 587 catch(negotiate_socks_connection(Address, StreamPair), 588 Error, 589 ( close(StreamPair, [force(true)]), 590 throw(Error) 591 )).
These correspond to the proxy methods defined by PAC Proxy auto-config. Additional methods can be returned if suitable clauses for http:http_connection_over_proxy/6 or try_proxy/4 are defined.
614:- multifile
615 proxy_for_url/3.
socket_create(SocketId, [type(dgram)])
or, explicit,
socket_create(SocketId, [domain(inet), type(dgram)])
.atom
, codes
,
string
(default) or term
(parse as Prolog term).octet
. iso_latin_1
, text
or utf8
.For example:
receive(Port) :- udp_socket(Socket), tcp_bind(Socket, Port), repeat, udp_receive(Socket, Data, From, [as(atom)]), format('Got ~q from ~q~n', [Data, From]), fail.
as(Type)
option of
udp_receive/4. The are interpreted differently though. No Type
corresponds to CVT_ALL of PL_get_chars(). Using atom
corresponds to CVT_ATOM and any of string or codes is mapped
to CVT_STRING|CVT_LIST, allowing for a SWI-Prolog string
object, list of character codes or list of characters.
Finally, term
maps to CVT_WRITE_CANONICAL. This implies that
arbitrary Prolog terms can be sent reliably using the option
list `[as(term)
,encoding(utf8)
])`, using the same option list
for udp_receive/4.For example
send(Host, Port, Message) :- udp_socket(S), udp_send(S, Message, Host:Port, []), tcp_close_socket(S).
A broadcast is achieved by using tcp_setopt(Socket, broadcast)
prior to sending the datagram and using the local network
broadcast address as a ip/4 term.
689 /******************************* 690 * OPTIONS * 691 *******************************/
setsockopt()
and the socket interface (e.g.,
socket(7)
on Linux) for details.
tcp_socket(Socket), tcp_setopt(Socket, bindtodevice(lo))
true
, disable the Nagle optimization on this socket,
which is enabled by default on almost all modern TCP/IP
stacks. The Nagle optimization joins small packages, which is
generally desirable, but sometimes not. Please note that the
underlying TCP_NODELAY setting to setsockopt()
is not
available on all platforms and systems may require additional
privileges to change this option. If the option is not
supported, tcp_setopt/2 raises a domain_error exception. See
Wikipedia
for details.setsockopt()
with the
corresponding arguments.swipl-win.exe
executable) this flags defines whether or not any events are
dispatched on behalf of the user interface. Default is
true
. Only very specific situations require setting
this to false
.fcntl()
call. Currently only suitable to deal
switch stream to non-blocking mode using:
tcp_fcntl(Stream, setfl, nonblock),
An attempt to read from a non-blocking stream while there is no
data available returns -1 (or end_of_file
for read/1), but
at_end_of_stream/1 fails. On actual end-of-input,
at_end_of_stream/1 succeeds.
769tcp_fcntl(Socket, setfl, nonblock) :-
770 !,
771 tcp_setopt(Socket, nonblock).
domain_error
exception.
inet
or inet6
to limit the results to the given
family.stream
or dgram
.true
(default false
), return the canonical host name
in the frist answerIn mode (+,-,+) Address is unified to a dict with the following keys:
inet
or inet6
. The underlying getaddrinfo()
calls
this family
. We use domain
for consistency with
socket_create/2.stream
or dgram
.canonname(true)
is specified on the first
returned address. Holds the official canonical host name.811host_address(HostName, Address, Options), ground(HostName) => 812 '$host_address'(HostName, Addresses, Options), 813 member(Address, Addresses). 814host_address(HostName, Address, Options), is_dict(Address) => 815 '$host_address'(HostName, Address.address, Options). 816host_address(HostName, Address, Options), ground(Address) => 817 '$host_address'(HostName, Address, Options).
getaddrinfo()
and the
IP-number is unified to Address using a term of the format
ip(Byte1,Byte2,Byte3,Byte4)
. Otherwise, if Address is bound to an
ip(Byte1,Byte2,Byte3,Byte4)
term, it is resolved by gethostbyaddr()
and the canonical hostname is unified with HostName.
832tcp_host_to_address(Host, Address), ground(Address) => 833 host_address(Host, Address, []). 834tcp_host_to_address(Host, Address), ground(Host) => 835 host_address(Host, [Dict|_], [domain(inet), type(stream)]), 836 Address = Dict.address.
gethostname()
and return the canonical name
returned by getaddrinfo()
.ip(A,B,C,D)
and ip6 addresses as ip(A,B,C,D,E,F,H)
. For example:
?- ip_name(ip(1,2,3,4), Name) Name = '1.2.3.4'. ?- ip_name(IP, '::'). IP = ip(0,0,0,0,0,0,0,0). ?- ip_name(IP, '1:2::3'). IP = ip(1,2,0,0,0,0,0,3).
859ip_name(Ip, Atom), ground(Atom) => 860 name_to_ip(Atom, Ip). 861ip_name(Ip, Atom), ground(Ip) => 862 ip_to_name(Ip, Atom). 863ip_name(Ip, _) => 864 instantiation_error(Ip). 865 866name_to_ip(Atom, Ip4) :- 867 split_string(Atom, '.', '', Parts), 868 length(Parts, 4), 869 maplist(string_byte, Parts, Bytes), 870 !, 871 Ip4 =.. [ip|Bytes]. 872name_to_ip(Atom, Ip6) :- 873 split_string(Atom, ':', '', Parts0), 874 clean_ends(Parts0, Parts1), 875 length(Parts1, Len), 876 ( Len < 8 877 -> append(Pre, [""|Post], Parts1), 878 Zeros is 8-(Len-1), 879 length(ZList, Zeros), 880 maplist(=("0"), ZList), 881 append([Pre, ZList, Post], Parts) 882 ; Len == 8 883 -> Parts = Parts1 884 ), 885 !, 886 maplist(string_short, Parts, Shorts), 887 Ip6 =.. [ip|Shorts]. 888name_to_ip(Atom, _) :- 889 syntax_error(ip_address(Atom)). 890 891clean_ends([""|T0], T) :- 892 !, 893 ( append(T1, [""], T0) 894 -> T = T1 895 ; T = T0 896 ). 897clean_ends(T0, T) :- 898 append(T1, [""], T0), 899 !, 900 T = T1. 901clean_ends(T, T). 902 903string_byte(String, Byte) :- 904 number_string(Byte, String), 905 must_be(between(0, 255), Byte). 906 907string_short(String, Short) :- 908 string_concat('0x', String, String1), 909 number_string(Short, String1), 910 must_be(between(0, 65535), Short). 911 912ip_to_name(ip(A,B,C,D), Atom) :- 913 !, 914 atomic_list_concat([A,B,C,D], '.', Atom). 915ip_to_name(IP, Atom) :- 916 compound(IP), 917 compound_name_arity(IP, ip, 8), 918 !, 919 IP =.. [ip|Parts], 920 ( zero_seq(Parts, Pre, Post, Len), 921 Len > 1, 922 \+ ( zero_seq(Post, _, _, Len2), 923 Len2 > Len 924 ) 925 -> append([Pre, [''], Post], Parts1), 926 ( Pre == [] 927 -> Parts2 = [''|Parts1] 928 ; Parts2 = Parts1 929 ), 930 ( Post == [] 931 -> append(Parts2, [''], Parts3) 932 ; Parts3 = Parts2 933 ) 934 ; Parts3 = Parts 935 ), 936 maplist(to_hex, Parts3, Parts4), 937 atomic_list_concat(Parts4, ':', Atom). 938ip_to_name(IP, _) :- 939 domain_error(ip_address, IP). 940 941zero_seq(List, Pre, Post, Count) :- 942 append(Pre, [0|Post0], List), 943 leading_zeros(Post0, Post, 1, Count). 944 945leading_zeros([0|T0], T, C0, C) => 946 C1 is C0+1, 947 leading_zeros(T0, T, C1, C). 948leading_zeros(L0, L, C0, C) => 949 L = L0, 950 C = C0. 951 952to_hex('', '') :- 953 !. 954to_hex(Num, Hex) :- 955 format(string(Hex), '~16r', [Num]). 956 957 958 959 /******************************* 960 * SOCKS * 961 *******************************/
ip(A,B,C,D)
: port973negotiate_socks_connection(Host:Port, StreamPair):- 974 format(StreamPair, '~s', [[0x5, % Version 5 975 0x1, % 1 auth method supported 976 0x0]]), % which is 'no auth' 977 flush_output(StreamPair), 978 get_byte(StreamPair, ServerVersion), 979 get_byte(StreamPair, AuthenticationMethod), 980 ( ServerVersion =\= 0x05 981 -> throw(error(socks_error(invalid_version(5, ServerVersion)), _)) 982 ; AuthenticationMethod =:= 0xff 983 -> throw(error(socks_error(invalid_authentication_method( 984 0xff, 985 AuthenticationMethod)), _)) 986 ; true 987 ), 988 ( Host = ip(A,B,C,D) 989 -> AddressType = 0x1, % IPv4 Address 990 format(atom(Address), '~s', [[A, B, C, D]]) 991 ; AddressType = 0x3, % Domain 992 atom_length(Host, Length), 993 format(atom(Address), '~s~w', [[Length], Host]) 994 ), 995 P1 is Port /\ 0xff, 996 P2 is Port >> 8, 997 format(StreamPair, '~s~w~s', [[0x5, % Version 5 998 0x1, % Please establish a connection 999 0x0, % reserved 1000 AddressType], 1001 Address, 1002 [P2, P1]]), 1003 flush_output(StreamPair), 1004 get_byte(StreamPair, _EchoedServerVersion), 1005 get_byte(StreamPair, Status), 1006 ( Status =:= 0 % Established! 1007 -> get_byte(StreamPair, _Reserved), 1008 get_byte(StreamPair, EchoedAddressType), 1009 ( EchoedAddressType =:= 0x1 1010 -> get_byte(StreamPair, _), % read IP4 1011 get_byte(StreamPair, _), 1012 get_byte(StreamPair, _), 1013 get_byte(StreamPair, _) 1014 ; get_byte(StreamPair, Length), % read host name 1015 forall(between(1, Length, _), 1016 get_byte(StreamPair, _)) 1017 ), 1018 get_byte(StreamPair, _), % read port 1019 get_byte(StreamPair, _) 1020 ; throw(error(socks_error(negotiation_rejected(Status)), _)) 1021 ). 1022 1023 1024 /******************************* 1025 * MESSAGES * 1026 *******************************/ 1027 1028/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 1029The C-layer generates exceptions of the following format, where Message 1030is extracted from the operating system. 1031 1032 error(socket_error(Code, Message), _) 1033- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ 1034 1035:- multifile 1036 prolog:error_message//1. 1037 1038prologerror_message(socket_error(_Code, Message)) --> 1039 [ 'Socket error: ~w'-[Message] ]. 1040prologerror_message(socks_error(Error)) --> 1041 socks_error(Error). 1042prologerror_message(proxy_error(tried(Tried))) --> 1043 [ 'Failed to connect using a proxy. Tried:'-[], nl], 1044 proxy_tried(Tried). 1045 1046socks_error(invalid_version(Supported, Got)) --> 1047 [ 'SOCKS: unsupported version: ~p (supported: ~p)'- 1048 [ Got, Supported ] ]. 1049socks_error(invalid_authentication_method(Supported, Got)) --> 1050 [ 'SOCKS: unsupported authentication method: ~p (supported: ~p)'- 1051 [ Got, Supported ] ]. 1052socks_error(negotiation_rejected(Status)) --> 1053 [ 'SOCKS: connection failed: ~p'-[Status] ]. 1054 1055proxy_tried([]) --> []. 1056proxy_tried([H|T]) --> 1057 proxy_tried(H), 1058 proxy_tried(T). 1059proxy_tried(error(Proxy, Error)) --> 1060 [ '~w: '-[Proxy] ], 1061 '$messages':translate_message(Error). 1062proxy_tried(false(Proxy)) --> 1063 [ '~w: failed with unspecified error'-[Proxy] ]
Network socket (TCP and UDP) library
The library(socket) provides TCP and UDP inet-domain sockets from SWI-Prolog, both client and server-side communication. The interface of this library is very close to the Unix socket interface, also supported by the MS-Windows winsock API. SWI-Prolog applications that wish to communicate with multiple sources have two options:
Client applications
Using this library to establish a TCP connection to a server is as simple as opening a file. See also http_open/3.
To deal with timeouts and multiple connections, threads, wait_for_input/3 and/or non-blocking streams (see tcp_fcntl/3) can be used.
Server applications
The typical sequence for generating a server application is given below. To close the server, use close/1 on AcceptFd.
There are various options for <dispatch>. The most commonly used option is to start a Prolog thread to handle the connection. Alternatively, input from multiple clients can be handled in a single thread by listening to these clients using wait_for_input/3. Finally, on Unix systems, we can use fork/1 to handle the connection in a new process. Note that fork/1 and threads do not cooperate well. Combinations can be realised but require good understanding of POSIX thread and fork-semantics.
Below is the typical example using a thread. Note the use of setup_call_cleanup/3 to guarantee that all resources are reclaimed, also in case of failure or exceptions.
Socket exceptions
Errors that are trapped by the low-level library are mapped to an exception of the shape below. In this term, Code is a lower case atom that corresponds to the C macro name, e.g.,
epipe
for a broken pipe. Message is the human readable string for the error code returned by the OS or the same as Code if the OS does not provide this functionality. Note that Code is derived from a static set of macros that may or may not be defines for the target OS. If the macro name is not known, Code isERROR_nnn
, where nnn is an integer.Note that on Windows Code is a
wsa*
code which makes it hard to write portable code that handles specific socket errors. Even on POSIX systems the exact set of errors produced by the network stack is not defined.Socket addresses (families)
The library supports both IP4 and IP6 addresses. On Unix systems it also supports Unix domain sockets (
AF_UNIX
). The address of a Unix domain sockets is a file name. Unix domain sockets are created using socket_create/2 or unix_domain_socket/1.IP4 or IP6 sockets can be created using socket_create/2 or tcp_connect/3 with the
inet
(default, IP3) orinet6
domain option. Some of the predicates produce or consume IP addresses as a Prolog term. The format of this term is one of:The predicate ip_name/2 translates between the canonical textual representation and the above defined address terms.
Socket predicate reference
*/