Main Page | Alphabetical List | Data Structures | File List | Data Fields | Globals | Related Pages

udpServer.c

Go to the documentation of this file.
00001 /******************************************************************************/
00002 /* This file has been written by Sergio Perez Alcañiz <serpeal@disca.upv.es>  */
00003 /*            Departamento de Informática de Sistemas y Computadores          */
00004 /*            Universidad Politécnica de Valencia                             */
00005 /*            Valencia (Spain)                                                */
00006 /*                                                                            */
00007 /* The RTL-lwIP project has been supported by the Spanish Government Research */
00008 /* Office (CICYT) under grant TIC2002-04123-C03-03                            */
00009 /******************************************************************************/
00010 
00011 #include <sys/types.h>
00012 #include <sys/socket.h>
00013 #include <netinet/in.h>
00014 #include <arpa/inet.h>
00015 #include <netdb.h>
00016 #include <stdio.h>
00017 #include <unistd.h> /* close() */
00018 #include <string.h> /* memset() */
00019 
00020 #define LOCAL_SERVER_PORT 7
00021 #define MAX_MSG 100
00022 
00023 int main(int argc, char *argv[]) {
00024   
00025   int sd, rc, n, cliLen;
00026   struct sockaddr_in cliAddr, servAddr;
00027   char msg[MAX_MSG];
00028 
00029   /* socket creation */
00030   sd=socket(AF_INET, SOCK_DGRAM, 0);
00031   if(sd<0) {
00032     printf("%s: cannot open socket \n",argv[0]);
00033     exit(1);
00034   }
00035 
00036   /* bind local server port */
00037   servAddr.sin_family = AF_INET;
00038   servAddr.sin_addr.s_addr = htonl(INADDR_ANY);
00039   servAddr.sin_port = htons(LOCAL_SERVER_PORT);
00040   rc = bind (sd, (struct sockaddr *) &servAddr,sizeof(servAddr));
00041   if(rc<0) {
00042     printf("%s: cannot bind port number %d \n", 
00043            argv[0], LOCAL_SERVER_PORT);
00044     exit(1);
00045   }
00046 
00047   printf("%s: waiting for data on port UDP %u\n", 
00048            argv[0],LOCAL_SERVER_PORT);
00049 
00050   /* server infinite loop */
00051   while(1) {
00052     
00053     /* init buffer */
00054     memset(msg,0x0,MAX_MSG);
00055 
00056 
00057     /* receive message */
00058     cliLen = sizeof(cliAddr);
00059     n = recvfrom(sd, msg, MAX_MSG, 0, 
00060                  (struct sockaddr *) &cliAddr, &cliLen);
00061 
00062     if(n<0) {
00063       printf("%s: cannot receive data \n",argv[0]);
00064       continue;
00065     }
00066       
00067     /* print received message */
00068     printf("%s: from %s:UDP%u : %s \n", 
00069            argv[0],inet_ntoa(cliAddr.sin_addr),
00070            ntohs(cliAddr.sin_port),msg);
00071     
00072   }/* end of server infinite loop */
00073 
00074 return 0;
00075 
00076 }

Generated on Wed Jan 14 12:58:57 2004 for RTL-lwIP-0.4 by doxygen 1.3.4