Datagrams are similar to mailslots and are used in
similar circumstances. There is no connection between the sender and
receiver, and there can be multiple receivers. Delivery to the receiver
is not ensured with either mailslots or datagrams, and successive
messages will not necessarily be received in the order they were sent.
The first step in using datagrams is to specify SOCK_DGRAM in the type field when creating the socket with the socket function.
Next, use sendto and recvfrom, which take the same arguments as send and recv, but add two arguments to designate the partner station. Thus, the sendto function is as follows.
int sendto ( SOCKET s, LPSTR lpBuffer, int nBufferLen, int nFlags, LPSOCKADDR lpAddr, int nAddrLen);
|
lpAddr points to an sockaddr
address structure where you can specify the name of a specific machine
and port, or you can specify that the datagram is to be broadcast to
multiple computers; see the next section.
When using recvfrom, you specify the computers (perhaps all) from which you are willing to accept datagrams; also see the next section.
As
with mailslots, datagram messages should be short; MSDN recommends 512
as the length limit for the data portion, as that limit avoids having
the message sent in fragments.
Datagram Broadcasting
Several steps are necessary to broadcast sendto messages to multiple computers. Here are the basic steps; see MSDN for complete details:
- Set the SOCK_DGRAM socket options by calling setsockopt, specifying the SO_BROADCAST option. Also, set this option for sockets that are to receive broadcast messages.
- Set the client’s lpAddr sin_addr_in.s_addr value to INADDR_BROADCAST.
- Set the port number as in the preceding examples.
- The broadcasts will be sent to and received by all computer interfaces (that is, all computers with a datagram socket with the SO_BROADCAST option) to that port.
Using Datagrams for Remote Procedure Calls
A
common datagram usage is to implement RPCs. Essentially, in the most
common situation, a client sends a request to a server using a
datagram. Because delivery is not ensured, the client will retransmit
the request if a response, also using a datagram, is not received from
the server after a wait period. The server must be prepared to receive
the same request several times.
The
important point is that the RPC client and server do not require the
overhead of a stream socket connection; instead, they communicate with
simple requests and responses. As an option, the RPC implementation
ensures reliability through time-outs and retransmissions, simplifying
the application program. Alternatively, the client and server are
frequently implemented so as to use stateless protocol
(they do not maintain any state information about previous messages),
so each request is independent of other requests. Again, application
design and implementation logic are greatly simplified.