User`s guide

186
K
A
DAK
KwikNet TCP/IP Sockets
UDP Sockets Examples
The following examples illustrate how a UDP socket can be used in a variety of
circumstances for different purposes.
Example 1
To use a UDP socket to communicate on a specific network with one and only one
foreign host, proceed as follows. Create a UDP socket and use kn_bind() to bind it to a
specific local IP address and port. Then call kn_connect() to establish a logical
connection with the foreign host's IP address and port. Use kn_recv() and kn_send() to
communicate using the socket.
Example 2
A variation of Example 1 will illustrate how logical connections can be manipulated.
Until a connection is established, function kn_send() cannot be used to send a datagram.
However, either kn_sendto() or kn_writev() can be used at any time to send a
datagram to any foreign host without affecting the logical connection. It should also be
noted that function kn_connect() can also be called to change the connection. The
connected foreign host is always used as the destination if a foreign address is not
explicitly provided in a request to send a datagram.
Example 3
To accept datagrams from only the foreign hosts to whom you send a datagram, proceed
as follows. Create a UDP socket and send a datagram to a foreign host using
kn_sendto() or kn_writev(). The socket is immediately given a unique port number
which will be known only to the foreign hosts with which you communicate. Your
socket will receive datagrams from any local network interface provided they are directed
to your particular port. Note that you cannot use function kn_send() to send datagrams
on this socket since the socket is not logically connected.
Note
KwikNet provides an alternate method of sending and
receiving UDP datagrams using the UDP channel API
described in Chapter 4.1. However, if you are familiar with
the use of the sockets API with sockets of type
SOCK_DGRAM, there is no compelling reason not to use UDP
sockets.