An Example Program for Receiving UDP Data

This example program (receive.c in the UDP directory) is similar to the server.c example program in the SOCKETS directory, except that we use SOCK_DGRAM instead of SOCK_STREAM for the second argument when calling socket. For both TCP and UDP, we use gethostbyname to resolve either a computer name or absolute IP address into a hostent struct. The setup of the struct sockaddr in_sin data and the call to bind is identical to the TCP socket example.

#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
char * host_name = “127.0.0.1”; // local host
void main() {
int sin_len;
int port = 8080;
char message[256];
int socket_descriptor;
struct sockaddr_in sin;
struct hostent *server_host_name;
server_host_name = gethostbyname(“127.0.0.1”);
bzero(&sin, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = htonl(INADDR_ANY);
sin.sin_port = htons(port);
// set socket using SOCK_DGRAM for UDP:
socket_descriptor = socket(PF_INET, SOCK_DGRAM, 0);
bind(socket_descriptor, (struct sockaddr *)&sin, sizeof(sin));
while (1) {
sin_len = sizeof(sin);
recvfrom(socket_descriptor, message, 256, 0,
(struct sockaddr *)&sin, &sin_len);
printf(“\nResponse from server:\n\n%s\n”, message);
if (strncmp(message, “stop”, 4) == 0) break;
}
close(socket_descriptor);
}

In this example, the while loop runs forever, until a message is received from the send.c example program that starts with the characters stop. In the TCP socket examples, we used recv, whereas here we use recvfrom. We use recvfrom when we want to receive data from a connectionless socket (like UDP). The fifth argument to recvfrom is the address of a struct sockaddr_in sin data object. The source address of this sockaddr_in object is filled in when receiving UDP messages, but the source address is not used in the example program.

Posted on: 18/12/2009








0 Comments
If you want to leave a comment please Login or Register