Datagram
The UDP protocol provides a mode of network communication whereby applications send packets of data, called datagrams to one another:
What is a Datagram?
Definition:
A datagram is an independent, self-contained message sent over the network whose arrival, arrival time, and content are not guaranteed.
Data Transfer
Datagram sockets are created in the same way as stream sockets (using the SOCK_DGRAM flag). They can use the same calls as stream sockets to send and receive data, except for the accept() and listen() calls.
The calls sendto() and recvfrom() are very useful to transfer data on datagram sockets:
sendto( s, buf, buflen, flags, &to, tolen);
It sends the content of buf to the address indicated in &to.
recvfrom( s, buf, buflen,flags, &from, &fromlen);
It receives a package and writes it to buf. The address of the sender is written to &from.
Writing a Datagram Client and Server
The Quote server
It waits for Datagram requests for quotes and servers them in Datagram packets.
Setting up the sockets:
sock = socket (AF_INET, SOCK_DGRAM, 0);
if (sock==-1) { ... }
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = 0;
if (bind (sock, (struct sockaddr *)&server, sizeof(server))
== -1){ perror("Binding datagram socket");...}
length = sizeof server;
if (getsockname (sock, (struct sockaddr *)&server, &length)
== -1){ perror("Getting socket name"); ... }
printf("Socket port # %d\n", ntohs(server.sin_port));The infinite loop:
- Section that receives the requests:
if ( recvfrom( sock, buf, 16, 0, (struct sockaddr *) &client, &length) == -1){ perror("Reading packet"); exit(1); }
- Section that constructs the responses:
quote= getquote();
if ( sendto( sock, quote, strlen(quote)+1, 0,
(struct sockaddr *) &client, sizeof client)
== -1) {
perror("Writing quota");
exit(0);
}The Client Application
Setting up sockets:
sock = socket (AF_INET, SOCK_DGRAM, 0);
if (sock == -1) { perror ("Opening Datagram socket");...}The client program sends a request to the server:
hp = gethostbyname(argv[1]);
if (hp == (struct hostent *) 0) {
perror("Unknown Host");
exit(0);
}
memcpy ((char*)&server.sin_addr, (char*) hp->h_addr,
hp->h_length);
server.sin_family = AF_INET;
server.sin_port = htons(atoi(argv[2]));
if( sendto( sock, DATA, sizeof DATA, 0,
(struct sockaddr *) &server, sizeof server)
== -1) { perror("Sending datagram message"); ... }The client gets a response from the server:
if (read( sock, buf, 1024) == -1)
perror("Receiving quotation");
exit(1);
}
printf("Quote of the Moment: %s\n", buf);
close(sock);Running the Client
Quote of the Moment: Life is wonderful. Without it we'd all be dead.