UDP Chat - User Datagram Protocol - Networks & DBMS Lab - C Program



Program :

// Server Program : udps.c

#include<stdio.h>
#include<string.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
main()
{
    struct sockaddr_in client,server;
    int s,n;
    char b1[100],b2[100];
    s=socket(AF_INET,SOCK_DGRAM,0);
    server.sin_family=AF_INET;
    server.sin_port=2000;
    server.sin_addr.s_addr=inet_addr("127.0.0.1");
    bind(s,(struct sockaddr *)&server,sizeof(server));
    printf("\nServer ready,waiting for client....\n");
    n=sizeof(client);
    while(1)
    {
        recvfrom(s,b1,sizeof(b1),0,(struct sockaddr *) &client,&n);
        if(!(strcmp(b1,"end")))
            break;
        printf("\nClient:%s",b1);
        printf("\nServer:");
        gets(b2);
        sendto(s,b2,sizeof(b2),0,(struct sockaddr *) &client,n);
              
    }
 
}

//Client Program : udpc.c

#include<stdio.h>
#include<string.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
main()
{
    struct sockaddr_in client,server;
    int s,n;
    char b1[100],b2[100];
    s=socket(AF_INET,SOCK_DGRAM,0);
    server.sin_family=AF_INET;
    server.sin_port=2000;
    server.sin_addr.s_addr=inet_addr("127.0.0.1");
    printf("\nClient ready....\n");
    n=sizeof(server);
    while(1)
    {
        printf("\nClient:");
        gets(b2);
        sendto(s,b2,sizeof(b2),0,(struct sockaddr *) &server,n);
        if(strcmp(b2,"end")==0)
            break;
        recvfrom(s,b1,sizeof(b1),0,NULL,NULL);
        printf("\nServer:%s",b1);
    }

}

Output:

Terminal 1: (Server)

student@cselab-desktop:~$ gcc udps.c -o server
/tmp/cc30up4j.o: In function `main':
udps.c:(.text+0x129): warning: the `gets' function is dangerous and should not be used.
student@cselab-desktop:~$ ./server

Server ready,waiting for client....

Client:hi...
Server:hi.. hw r u?
   
Client:fine.u?
Server:ok.bye...
     
Client:bye...
Server:end
student@cselab-desktop:~$

Terminal 2 :(Client)
student@cselab-desktop:~$ gcc udpc.c -o client
/tmp/ccfz7pFY.o: In function `main':
udpc.c:(.text+0x8b): warning: the `gets' function is dangerous and should not be used.
student@cselab-desktop:~$ ./client

Client ready....

Client:hi...

Server:hi.. hw r u?
Client:fine.u?

Server:ok.bye...
Client:bye...

   
Server:end
Client:student@cselab-desktop:~$

0 comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...