udp server and client


 client 


#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
int main()
{
 int sfd = socket(AF_INET,SOCK_DGRAM,0);
 if(sfd == -1)
 {
  perror("socked failed : ");
  exit(1);
 }
 else
 {
  printf("socket created successfully : sfd : %d\n",sfd);
 while(1)
 {
  struct sockaddr_in server;
  server.sin_family = AF_INET;
  server.sin_port = htons(8000);
  server.sin_addr.s_addr = inet_addr("192.168.0.122");
  char buff[50] = "";
  printf("enter the message to server : \n");
  fgets(buff,50,stdin);
  int snd = sendto(sfd,buff,sizeof(buff),0,(struct sockaddr *)&server,sizeof(server));
  if(snd == -1)
  {
   perror(" sendto failed : ");
   exit(1);
  }
  else
  {
   printf("send successful\n");
  }
  printf("waiting for message from server :\n");
// char buff[50] = "";
 int len = sizeof(server);
 int r = recvfrom(sfd,buff,sizeof(buff),0,(struct sockaddr *)&server,&len);
 if(r == -1)
 {
  perror("recvfrom failed : ");
  exit(1);
 }
 else
 {
  printf("message from server : %s\n",buff);
 }
 }
}
}

server


#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
int main()
{
 int sfd = socket(AF_INET,SOCK_DGRAM,0);
 if(sfd == -1)
 {
  perror("socked failed : ");
  exit(1);
 }
 else
 {
  printf("socket created successfully : sfd : %d\n",sfd);
  struct sockaddr_in server,client;
  server.sin_family = AF_INET;
  server.sin_port = htons(8000);
  server.sin_addr.s_addr = INADDR_ANY;
  int b = bind(sfd,(struct sockaddr *)&server,sizeof(server));
  if(b == -1)
  {
   perror(" bind failed : ");
   exit(1);
  }
  else
  {
   printf("bind successful\n");
   while(1)
   {
    char buff[50] = "";    
    printf("waiting for message from client :\n");
    //      char buff[50] = "";    
    int len = sizeof(client);
    int r = recvfrom(sfd,buff,sizeof(buff),0,(struct sockaddr *)&client,&len);
    if(r == -1)
    {
     perror("recvfrom failed : ");
     exit(1);
    }
    else
    {
     printf("message from client : %s : %s \n",inet_ntoa(client.sin_addr),buff);
    }
   

   printf("enter the message to server : \n");
   fgets(buff,50,stdin);
   int snd = sendto(sfd,buff,sizeof(buff),0,(struct sockaddr *)&client,sizeof(client));
   if(snd == -1)
   {
    perror(" sendto failed : ");
    exit(1);
   }
   else
   {
    printf("send successful\n");
   }
  }
 }
 }
 }

Comments

Popular posts from this blog

TCP SERVER program