My Tech notes: UDP Traffic Generator Server Side C code

Unix Documentation

Free Online Unix Training Materials

Lists many links to free Unix training materials.

Pointers and Arrays Materials

Pointers and Arrays materials Explained for C beginners

C FAQ and General Questions C Interview Questions

Powered By

Free XML Skins for Blogger

Powered by Blogger

Thursday, April 2, 2009

UDP Traffic Generator Server Side C code

Learning Networking basics using C programs, to start with here is simple UDP server side code,
Why to start with UDP because its simple, no need of connection handshake like TCP.

udp server

#include <sys/types.h>;
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <unistd.h>/* close() */
#include <string.h> /* memset() */

#define LOCAL_SERVER_PORT 1500
#define MAX_MSG 1500

int main() {

int sd, rc, n, cliLen;
struct sockaddr_in cliAddr, servAddr;
char msg[MAX_MSG];
int count;
int prev_count=0;
/* socket creation */
sd=socket(AF_INET, SOCK_DGRAM, 0); //create unix socket
printf("cannot open socket \n");

/* bind local server port */
servAddr.sin_family = AF_INET;
servAddr.sin_addr.s_addr = inet_addr(""); //using fixed IP for simplicity
servAddr.sin_port = htons(LOCAL_SERVER_PORT);
rc = bind (sd, (struct sockaddr *) &servAddr,sizeof(servAddr));
printf("cannot bind port number %d \n", LOCAL_SERVER_PORT);

printf("waiting for data on port UDP %u\n",

/* server infinite loop */
while(1) {

/* receive message */
cliLen = sizeof(cliAddr);
n = recvfrom(sd, msg, MAX_MSG, 0,
(struct sockaddr *) &cliAddr, &cliLen);

printf("cannot receive data \n");

/* print received message */
printf("from %s:UDP%u: count:%d message: %s\n",

}/* end of server infinite loop */

return 0;


rickster said...


Good work, but aren't you missing a call to the function listen() before de while(1) loop??

Bhagwat said...

Thanks to rickster..for valuable suggestion.

Post a Comment