buffer - receiving a web page from web server in a c program -


here code web page server (actually google.com):

#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <string.h> #include <unistd.h>  char http[] = "get / http/1.1\naccept: */*\nhost: www.google.com\naccept-charset: utf-8\nconnection: keep-alive\n\n"; char page[bufsiz];  int main(int argc, char **argv) {     struct addrinfo hint, *res, *res0;      char *address = "www.google.com";     char *port = "80";      int ret, sockfd;      memset(&hint, '\0', sizeof(struct addrinfo));      hint.ai_family = af_inet;     hint.ai_socktype = sock_stream; /*  hint.ai_protocol = ipproto_tcp; */      if((ret = getaddrinfo(address, port, &hint, &res0)) < 0)     {         perror("getaddrinfo()");         exit(exit_failure);     }      for(res = res0; res; res = res->ai_next)     {         sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);          if(-1 == sockfd)         {             perror("socket()");             continue;         }          ret = connect(sockfd, res->ai_addr, res->ai_addrlen);          if(-1 == ret)         {             perror("connect()");             sockfd = -1;             continue;         }          break;      }      if(-1 == sockfd)     {         printf("can't connect server...");         exit(exit_failure);     }      send(sockfd, http, strlen(http), 0);      recv(sockfd, page, 1023, 0);      printf("%s\n", page);      return 0; } 

i've defined array of 'bufsiz' chars in order store web page. bufsiz 1024 character on operating system , therefor, can store web page 1024 char length. if page larger 1024? mean, how can store page larger 1024 character? define array of 2048, 4096 or 10,000 chars, think not conventional way.

thanks.

one typical solution call recv(2) in loop , keep processing (printing ?) received bytes. way can receive pages of size.

ssize_t nread;  while ((nread = recv(sockfd, page, sizeof page, 0)) > 0) {     /* .... */ }  if (nread < 0)     perror("recv"); 

Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -