sockets - select blocks forever in helloworld type program -


#include <stdio.h> #include <stdlib.h> #include <unistd.h>  #include <netdb.h> #include <netinet/in.h>  #include <string.h>  int main(int argc, char *argv[]) {     int sock, portno, n;     struct sockaddr_in serv_addr;     struct hostent *server;     const char* host = "www.google.com";     portno = 80;      sock = socket(af_inet, sock_stream, 0);     if (sock < 0) {         perror("error opening socket");         exit(1);     }      server = gethostbyname(host);     if (server == null) {         fprintf(stderr,"error, no such host\n");         exit(0);     }      bzero((char *) &serv_addr, sizeof(serv_addr));     serv_addr.sin_family = af_inet;     bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length);     serv_addr.sin_port = htons(portno);      if (connect(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) {         perror("error connecting");         exit(1);     }      printf("connected\n");      const char* = "get /index.html http/1.1\n\n";     n = write(sock, get, strlen(get));     printf("writen %i %i\n", n, sock);      fd_set rs;     fd_zero(&rs);     fd_set(sock, &rs);  /*     if uncommented, code works     while (true) {         char ch;         recv(sock, &ch, 1, 0);         printf("%c", ch);     } */      int ret = select(1, &rs, 0, 0, 0);// block forecer      if (fd_isset(sock, &rs)) {         char ch;         int count = recv(sock, &ch, 1, 0);         if (count >= 0) {             printf("%c", ch);         }     }     return 0; } 

this simple example block on select(). if try read recv() without using select() first, read successfully, data ready. why select() blocks?

the problem classical, wrong first argument select():

instead of

 select(1, &rs, 0, 0, 0); 

use

 select(sock + 1, &rs, 0, 0, 0); 

Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -