6 library(socket): Network socket (TCP and UDP) library
AllApplicationManualNameSummaryHelp

  • Documentation
    • Reference manual
    • Packages
      • SWI-Prolog C-library
        • library(socket): Network socket (TCP and UDP) library
          • Client applications
          • Server applications
          • Socket exceptions
          • TCP socket predicates
          • UDP protocol support
            • udp_socket/1
            • udp_receive/4
            • udp_send/4

6.5 UDP protocol support

The current library provides limited support for UDP packets. The UDP protocol is a connection-less and unreliable datagram based protocol. That means that messages sent may or may not arrive at the client side and may arrive in a different order as they are sent. UDP messages are often used for streaming media or for service discovery using the broadcasting mechanism.

udp_socket(-Socket)
Similar to tcp_socket/1, but create a socket using the SOCK_DGRAM protocol, ready for UDP connections.
udp_receive(+Socket, -Data, -From, +Options)
Wait for and return the next datagram. The data is returned as a Prolog string object (see string_to_list/2). From is a term of the format ip(A,B,C,D):Port indicating the sender of the message. Socket can be waited for using wait_for_input/3. Defined Options:
as(+Type)
Defines the returned term-type. Type is one of atom, codes or string (default).
max_message_size(+Size)
Specify the maximum number of bytes to read from a UDP datagram. Size must be within the range 0-65535. If unspecified, a maximum of 4096 bytes will be read.

The typical sequence to receive UDP data is:

receive(Port) :-
        udp_socket(S),
        tcp_bind(S, Port),
        repeat,
            udp_receive(Socket, Data, From, [as(atom)]),
            format('Got ~q from ~q~n', [Data, From]),
            fail.
udp_send(+Socket, +Data, +To, +Options)
Send a UDP message. Data is a string, atom or code-list providing the data. To is an address of the form Host:Port where Host is either the hostname or a term ip/4. Options is currently unused.

A simple example to send UDP data is:

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.

The normal mechanism to discover a service on the local network is for the client to send a broadcast message to an agreed port. The server receives this message and replies to the client with a message indicating further details to establish the communication.