Home
 
 
Search:  
C C++ Perl PHP Python HTML ShellScripts
 
 
  Coding Books
  Tutorials
  Search Code
  Browse Code
  Link to Us
  Site News
  Contact Metalshell
 
 
 
  Submit Code   Statistics
 



Effective TCP/IP Programming: 44 Tips to Improve Your Network Programs    (ISBN: 0201615894)


 

 List Price: $34.95
 Our Price: $34.95
 Used Price: $12.50

 Release Date: 15 January, 2000
 Manufacturer: Addison-Wesley Pub Co (Paperback)
 Sales Rank: 61,739

 Author: Jon C. Snader









More Info

 Web Client 2002-01-07 18:59:26
 
Category: source:c:internet
Description: Makes a connection to httpd server and reads html source
Platform: unix
Author: detour
Viewed: 5812
Rating: 4.2/5 (38 votes)
If you have any questions about this piece of code or still need help, try posting your question on the forum.

 

Printable Version
webclient.c
/* webclient.c written by detour@metalshell.com
 *
 * This code will connect to a host and attempt to download
 * the source for an http page.  
 *
 * run: ./webclient <host>
 *
 * http://www.metalshell.com/
 *
 */


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

#define PROTOCOL "tcp"
#define SERVICE "http"
#define GET "GET / HTTP/1.0\n\n"

int main(int argc, char *argv[]) {
  int sockid;
  int bufsize;
  char host[50];
  char buffer[1024];
  struct sockaddr_in socketaddr;
  struct hostent *hostaddr;
  struct servent *servaddr;
  struct protoent *protocol;

  strcpy(host, argv[1]);

  /* Resolve the host name */
  if (!(hostaddr = gethostbyname(host))) {
    fprintf(stderr, "Error resolving host.");
    exit(1);
  }

  /* clear and initialize socketaddr */
  memset(&socketaddr, 0, sizeof(socketaddr));
  socketaddr.sin_family = AF_INET;

  /* setup the servent struct using getservbyname */
  servaddr = getservbyname(SERVICE, PROTOCOL);
  socketaddr.sin_port = servaddr->s_port;

  memcpy(&socketaddr.sin_addr, hostaddr->h_addr, hostaddr->h_length);

  /* protocol must be a number when used with socket()
     since we are using tcp protocol->p_proto will be 0 */
  protocol = getprotobyname(PROTOCOL);

  sockid = socket(AF_INET, SOCK_STREAM, protocol->p_proto);
  if (sockid < 0) {
    fprintf(stderr, "Error creating socket.");
    exit(1);
  }

  /* everything is setup, now we connect */
  if(connect(sockid, &socketaddr, sizeof(socketaddr)) == -1) {
    fprintf(stderr, "Error connecting.");
    exit(1);
  }

  /* send our get request for http */
  if (send(sockid, GET, strlen(GET), 0) == -1) {
    fprintf(stderr, "Error sending data.");
    exit(1);
  }

  /* read the socket until its clear then exit */
  while ( (bufsize = read(sockid, buffer, sizeof(buffer) - 1))) {
    write(1, buffer, bufsize);
  }

  close(sockid);
}
Rate this code:
(Not Helpful)  (Very Helpful) 

 
 
   Developer.*  
   Blue Parrots  
   Technipal  
   Defy Magazine  
   Code Project  
   Prog. Heaven  


Got Money?