Rabu, 22 September 2010

IMPLEMENTATION OF UDP ( Universal Datagram Protocol ) Programs

IMPLEMENTATION OF UDP

PROGRAM:



CLIENT:



#include

#include

#include

#include

#include

#include

#include

#include

#include

#define REMOTE_SERVER_PORT 1896s

#define MAX_MSG 100

int main(int argc,char*argv[])

{

int sd,rc,i;

struct sockaddr_in cliaddr,remoteservaddr;

struct hostent *h;

if(argc<3)

{

printf("Usage:%s..\n",argv[0]);

exit(1);

}

h=gethostbyname(argv[1]);

if(h==NULL)

{

printf("%s:unknown host%s\n",argv[0],argv[1]);

exit(1);

}

printf("%s:sending data to '%s'(IP:%s)\n",argv[0],h->h_name,inet_ntoa(*(struct i

n_addr*)h->h_addr_list[0]));

remoteservaddr.sin_family=h->h_addrtype;

memcpy((char*)&remoteservaddr.sin_addr.s_addr,h->h_addr_list[0],h->h_length);

remoteservaddr.sin_port=htons(REMOTE_SERVER_PORT);

sd=socket(AF_INET,SOCK_DGRAM,0);

if(sd<0)

{

printf("%s:cannot open socket\n",argv[0]);

exit(1);

}

cliaddr.sin_family=AF_INET;

cliaddr.sin_addr.s_addr=htonl(INADDR_ANY);

cliaddr.sin_port=htons(0);

rc=bind(sd,(struct sockaddr*)&cliaddr,sizeof(cliaddr));

if(rc<0)

{

printf("%s:cannot bindport\n",argv[0]);

exit(1);

}

for(i=2;i
{

rc=sendto(sd,argv[i],strlen(argv[i])+1,0,(struct sockaddr*)&remoteservaddr,sizeo

f(remoteservaddr));

if(rc<0)

{

printf("%s:cannot send data%d\n",argv[0],i-1);

close(sd);

exit(1);

}

}

return 1;

}





SERVER:



#include

#include

#include

#include

#include

#include

#include

#define LOCAL_SERVER_PORT 1896

#define MAX_MSG 100

int main(int argc,char *argv[])

{

int sd,rc,n,clilen;

struct sockaddr_in cliaddr,servaddr;

char msg[MAX_MSG];

sd=socket(AF_INET,SOCK_DGRAM,0);

if(sd<0)

{

printf("%s:cannot open socket\n",argv[0]);

exit(1);

}

servaddr.sin_family=AF_INET;

servaddr.sin_addr.s_addr=htonl(INADDR_ANY);

servaddr.sin_port=htons(LOCAL_SERVER_PORT);

rc=bind(sd,(struct sockaddr*)&servaddr,sizeof(servaddr));

if(rc<0)

{

printf("%s:cannot bind port number %d\n",argv[0],LOCAL_SERVER_PORT);

exit(1);

}

printf("%s:waiting for data on port UDP%u\n",argv[0],LOCAL_SERVER_PORT);

while(1)

{

memset(msg,0x0,MAX_MSG);

clilen=sizeof(cliaddr);

n=recvfrom(sd,msg,MAX_MSG,0,(struct sockaddr*)&cliaddr,&clilen);

if(n<0)

{

printf("%s:cannot receive data\n",argv[0]);

continue;

}

printf("%s:from%s:UDP%u:%s\n",argv[0],inet_ntoa(cliaddr.sin_addr),ntohs(cliaddr.

sin_port),msg);

}

return 0;

}

















































OUTPUT:



IN SERVER:



[testciet @linuxcentre ~]$ ./a.out

./a.out:waiting for data on port UDP1896

./a.out:from127.0.0.1:UDP32771:hi ……





IN CLIENT:



[testciet@linuxcentre ~]$ ./a.out localhost hi ……

./a.out:sending data to 'linuxcentre'(IP:127.0.0.1)







CIET college Programs,LAB Programs for Engineering Students,Computer Networks LAB Programs,Remoboys,karthik,Remokn,Student3k,TCP programs source code


Related Posts Plugin for WordPress, Blogger...