hok00age

Simple downloader using C

Jun 8th, 2011
284
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.82 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <sys/types.h>
  3. #include <sys/socket.h>
  4. #include <netinet/in.h>
  5. #include <netdb.h>
  6. #include <stdlib.h>
  7. #include <string.h>
  8. #include <unistd.h>
  9.  
  10. int main(int argc, char** argv)
  11. {
  12.     struct sockaddr_in servaddr;
  13.     struct hostent *hp;
  14.     int sock_id;
  15.     char message[1024*1024] = {0};
  16.     int msglen;
  17.     char request[] = "GET /index.html HTTP/1.0\n"
  18.     "From: slava!!!\nUser-Agent: wget_sortof by slava\n\n";
  19.  
  20.     //Get a socket
  21.     if((sock_id = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
  22.         fprintf(stderr,"Couldn't get a socket.\n"); exit(EXIT_FAILURE);
  23.     }
  24.     else {
  25.         fprintf(stderr,"Got a socket.\n");
  26.     }
  27.  
  28.     //book uses bzero which my man pages say is deprecated
  29.     //the man page said to use memset instead. :-)
  30.     memset(&servaddr,0,sizeof(servaddr));
  31.  
  32.     //get address for google.com
  33.     if((hp = gethostbyname("google.com")) == NULL) {
  34.         fprintf(stderr,"Couldn't get an address.\n"); exit(EXIT_FAILURE);
  35.     }
  36.     else {
  37.         fprintf(stderr,"Got an address.\n");
  38.     }
  39.  
  40.     //bcopy is deprecated also, using memcpy instead
  41.     memcpy((char *)&servaddr.sin_addr.s_addr, (char *)hp->h_addr, hp->h_length);
  42.  
  43.     //fill int port number and type
  44.     servaddr.sin_port = htons(80);
  45.     servaddr.sin_family = AF_INET;
  46.  
  47.     //make the connection
  48.     if(connect(sock_id, (struct sockaddr *)&servaddr, sizeof(servaddr)) != 0) {
  49.         fprintf(stderr, "Couldn't connect.\n");
  50.     }
  51.     else {
  52.         fprintf(stderr,"Got a connection!!!\n");
  53.     }
  54.  
  55.     //NOW THE HTTP PART!!!
  56.  
  57.     //send the request
  58.     write(sock_id,request,strlen(request));
  59.  
  60.     //read the response
  61.     msglen = read(sock_id,message,1024*1024);
  62.  
  63.     printf("response is %d bytes long\n", msglen);
  64.  
  65.     //print the reasponse
  66.     printf("%s", message);
  67.  
  68.     return 0;
  69. }
Add Comment
Please, Sign In to add comment