UDP/IPv4 Client & Server applications

UDP Client

The client sends packets on the network.

/* $Id$ 
 * 
 *
 * 
 * 
 */

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdlib.h>
#include <arpa/inet.h>

#define MAXBUF 65536

int main(int argc, char* argv[])
{
   int sock;
   int status;
   struct addrinfo sainfo, *psinfo;
   struct sockaddr_in sinaddr;
   int sinlen;
   char buffer[MAXBUF];

   sinlen = sizeof(struct sockaddr_in);

   if(argc < 2)
     printf("Specify a port number\n"), exit(1);

   sock = socket(PF_INET, SOCK_DGRAM,0);

   memset(&sinaddr, 0, sizeof(struct sockaddr_in));
   sinaddr.sin_port = htons(0);
   sinaddr.sin_family = AF_INET;
   sinaddr.sin_addr.s_addr = INADDR_ANY;

   status = bind(sock, (struct sockaddr *)&sinaddr, sinlen);

   if(-1 == status)
     perror("bind"), exit(1);

   memset(&sainfo, 0, sizeof(struct addrinfo));
   memset(&sinaddr, 0, sinlen);

   sainfo.ai_flags = 0;
   sainfo.ai_family = PF_INET;
   sainfo.ai_socktype = SOCK_DGRAM;
   sainfo.ai_protocol = IPPROTO_UDP;
   status = getaddrinfo("localhost", argv[1], &sainfo, &psinfo);

   switch (status) 
     {
      case EAI_FAMILY: printf("family\n");
        break;
      case EAI_SOCKTYPE: printf("stype\n");
        break;
      case EAI_BADFLAGS: printf("flag\n");
        break;
      case EAI_NONAME: printf("noname\n");
        break;
      case EAI_SERVICE: printf("service\n");
        break;
     }
   sprintf(buffer,"Ciao");

   status = sendto(sock, buffer, strlen(buffer), 0,
                     (struct sockaddr *)psinfo->ai_addr, sinlen);

   printf("buffer : %s \t%d\n", buffer, status);

   // free memory
   freeaddrinfo(psinfo);
   psinfo = NULL;

   shutdown(sock, 2);
   close(sock);
   return 0;
}

UDP Server

The server listens for incoming packets.

/* $Id$ 
 * 
 *
 * 
 * 
 */

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdlib.h>

#define MAXBUF 65536

int main()
{
   int sock;
   int status;
   struct sockaddr_in sinaddr;
   int sinlen;
   char buffer[MAXBUF];

   sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);

   sinlen = sizeof(struct sockaddr_in);

   memset(&sinaddr, 0, sinlen);

   /* just use the first address returned in the structure */

   sinaddr.sin_port = htons(0);
   sinaddr.sin_family = AF_INET;
   sinaddr.sin_addr.s_addr = INADDR_ANY;

   status = bind(sock, (struct sockaddr *)&sinaddr, sinlen);
   if(-1 == status)
     perror("bind"), exit(1);

   status = getsockname(sock, (struct sockaddr *)&sinaddr, &sinlen);

   printf("%d\n", ntohs(sinaddr.sin_port));

   status = recvfrom(sock, buffer, MAXBUF, 0, 
                     (struct sockaddr *)&sinaddr, &sinlen);
   printf("buffer : %s\n", buffer);

   shutdown(sock, 2);
   close(sock);
   return 0;
}