Implementation Of Udp Client Server Communication Using Bind System Call C Program

Algorithm Steps:
Server:
1. Create a socket using socket() system call.
2. Bind socket to port number using bind() system call.
3. Inside a loop wait for the client to send some message.
4. Receive a message using recvfrom() system call.
5. If received message is ‘bye’, send message ‘bye’ and stop the chat.  If not, send some message using sendto() system call.

Client:
1. Create a socket using socket() system call.
2. Inside a loop, type a message to be send to server.
3. Send the message using sendto() system call.
4. Receive the message from server using recvfrom() system call.
5. If the message received or send is ‘bye’ then stop.
6. Close the socket.
7. Stop.
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<string.h>
int main(int argc, char **argv)
{
int sockfd;
struct sockaddr_in mysock, newsock;
if((sockfd=socket(AF_INET,SOCK_DGRAM,0))<0)
{
perror(“\nNo socket”);
exit(0);
}
size=sizeof(struct sockaddr);
socklen_t len=sizeof(newsock);
bzero(&mysock, size);
mysock.sin_family=AF_INET;
mysock.sin_port=htons(4001);
mysock.sin_addr.s_add=htonl(INADDR_ANY);
if((bind(sockfd,(struct sockaddr *)&mysock, size))<0)
{
    perror(“\n No bind”);
    exit(0);
}
printf(“\nUDP socket created……..listening port 4001”);
while(strcmp(msg,”bye”)!=0)
{
    if((val=recvfrom(sockfd, msg, 1024,0,(struct sockaddr *)$newsock, $len))<0)
    {
        perror(“\nNot created”);
        exit(0);
    }
    else
    {
        printf(“\nServer received the message : %s”, msg);
    }
   
    printf(“\nFrom client:”);
    printf(“%s”,msg);
   
    if(strcmp(msg,”bye”)==0)
    {
        printf(“\nServer:”);
        scanf(“%s”,msg);
        exit(0);
    }
    printf(“\nServer:”);
    scanf(“%s”,msg);
    if((sendto(sockfd, msg, val, 0, (struct sockaddr*)&newsock,len))<0)
    {
        perror(“\nNo message”);
        exit(0);
    }
}
close(sockfd);
return 0;
}
OUTPUT:
cc udpser.c
./a.out
UDP socket created……...listening port 4001
Server received the message: hello
From client: hello
Server: hey
Server received the message: HowRU?
From client: HowRU?
Server: fine.
Server received the message: bye
From client: bye
Server: bye

Post a Comment

0 Comments