linux - C socket recieves data then does not send it -


i have created simple socket connection sends request node.js app , receives random data , sends data sends , receives data correctly not send random data

char *httpbody; struct addrinfo hints, *result; const char *host = "localhost"; char user[512] = "test@gmail.com"; char pass[512] = "test"; char headers[512]; srand(time(null));  memset(&hints, 0, sizeof(hints));  hints.ai_family = af_inet; hints.ai_socktype = sock_stream;  if (getaddrinfo(host, "3000", &hints, &result) != 0) {     freeaddrinfo(result);     perror("could not resolve hostname.");     exit(1); }  int newsocket = socket(result->ai_family, result->ai_socktype, 0); if (newsocket == -1) {     perror("could not create socket.");     freeaddrinfo(result);     close(newsocket);     exit(1); }  if (connect(newsocket, result->ai_addr, result->ai_addrlen) == -1) {     perror("could not connect.");     freeaddrinfo(result);     close(newsocket);     exit(1); }  sprintf(headers, "get /auth?user=%s&pass=%s http/1.1\r\n"         "user-agent: device\r\n"         "accept-language: de,en;q=0.7,en-us;q=0.3\r\n"         "content-type: text/html; charset=utf-8\r\n"         "connection: close\r\n\r\n", user, pass);  if ((send(newsocket, headers, strlen(headers), 0)) == -1) {     perror("could not send data.");     freeaddrinfo(result);     close(newsocket);     exit(1); }  char response[51201] = ""; recv(newsocket, response, 51200, 0); response[strlen(response)] = '\0';  httpbody = strstr(response, "\r\n\r\n"); if (httpbody) {     httpbody += 8; }  int data = rand() % 255 + 1;  sprintf(headers, "get /add_data?user=%s&data=%i&"         "uid=%s http/1.1\r\n"         "user-agent: device\r\n"         "accept-language: de,en;q=0.7,en-us;q=0.3\r\n"         "content-type: text/html; charset=utf-8\r\n"         "connection: close\r\n\r\n", user, data, httpbody);  if ((send(newsocket, headers, strlen(headers), 0)) == -1) {     perror("could not send data.");     freeaddrinfo(result);     close(newsocket);     exit(1); }  printf("done");  freeaddrinfo(result); close(newsocket); 

when remove revc request works fine , not show errors , lost

check lines of code:

recv(newsocket, response, 51200, 0); response[strlen(response)] = '\0';` 

recv doesn't return null-terminated data, cannot use strlen determine size of data. must use return value of recv instead:

int data_size = recv(newsocket, response, 51200, 0); 

Comments

Popular posts from this blog

javascript - Count length of each class -

What design pattern is this code in Javascript? -

hadoop - Restrict secondarynamenode to be installed and run on any other node in the cluster -