Problem in udp socket programing in c

Posted by Md. Talha on Programmers See other posts from Programmers or by Md. Talha
Published on 2012-10-08T15:37:44Z Indexed on 2012/10/08 15:51 UTC
Read the original article Hit count: 210

Filed under:

I complile the following C code of UDP client after I run './udpclient localhost 9191' in terminal.I put "Enter Text= " as Hello, but it is showing error in sendto as below:

Enter text: hello 
hello
 : error in sendto()guest-1SDRJ2@md-K42F:~/Desktop$ 

"

Note: I open 1st the server port as below in other terminal ./server 9191. I beleive there is no error in server code. The udp client is not passing message to server. If I don't use thread , the message is passing .But I have to do it by thread.

UDP client Code:

/* simple UDP echo client */

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <pthread.h>

#define STRLEN 1024

static void *readdata(void *);
static void *writedata(void *);
  int sockfd, n, slen;
struct sockaddr_in servaddr;
char sendline[STRLEN], recvline[STRLEN];

int main(int argc, char *argv[]) {
  pthread_t  readid,writeid;

  struct sockaddr_in servaddr;
  struct hostent *h;

  if(argc != 3) {
    printf("Usage: %s <proxy server ip> <port>\n", argv[0]);
    exit(0);
  }

  /* create hostent structure from  user entered host name*/
  if ( (h = gethostbyname(argv[1])) == NULL) {
    printf("\n%s: error in gethostbyname()", argv[0]);
    exit(0);
  }

  /* create server address structure */
  bzero(&servaddr, sizeof(servaddr)); /* initialize it */
  servaddr.sin_family = AF_INET;
  memcpy((char *) &servaddr.sin_addr.s_addr, h->h_addr_list[0], h->h_length);
  servaddr.sin_port = htons(atoi(argv[2])); /* get the port number from argv[2]*/

  /* create a UDP socket: SOCK_DGRAM */
  if ( (sockfd = socket(AF_INET,SOCK_DGRAM, 0)) < 0) {
    printf("\n%s: error in socket()", argv[0]);
    exit(0);
  }


  pthread_create(&readid,NULL,&readdata,NULL);
  pthread_create(&writeid,NULL,&writedata,NULL);

  while(1)
  {
  };

  close(sockfd);
}

static void * writedata(void *arg)
 {
 /* get user input */
  printf("\nEnter text: ");

  do {
      if (fgets(sendline, STRLEN, stdin) == NULL) {
        printf("\n%s: error in fgets()");
        exit(0);
      }
      /* send a text */
      if (sendto(sockfd, sendline, sizeof(sendline), 0, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0) {
          printf("\n%s: error in sendto()");
          exit(0);
      }
     }while(1);
}

static void * readdata(void *arg)
{
  /* wait for echo */
  slen = sizeof(servaddr);
  if ( (n = recvfrom(sockfd, recvline, STRLEN, 0, (struct sockaddr *) &servaddr, &slen)) < 0) {
      printf("\n%s: error in recvfrom()");
      exit(0);
  }

  /* null terminate the string */
  recvline[n] = 0;

  fputs(recvline, stdout);


}

© Programmers or respective owner

Related posts about programming-languages