HTTPクライアント

戻る

::::::::::::::
Makefile
::::::::::::::
# $Id: http-client.html,v 1.1 2009/06/22 16:12:13 kishi Exp kishi $

CFLAGS = -c -Wall -O2
OBJECT = HttpClient.o getConnection.o
EXE = HttpClient.exe

$(EXE): $(OBJECT)
	gcc $(OBJECT) -o $(EXE) && strip $(EXE)

HttpClient.o:  HttpClient.c
	gcc $(CFLAGS) HttpClient.c

getConnection.o:  getConnection.c
	gcc $(CFLAGS) getConnection.c

clean:
	rm -f *.o *.exe *~ *.bak

indent:
	indent -br *.c
::::::::::::::
common.h
::::::::::::::
int getConnection(char* hostname);

::::::::::::::
HttpClient.c
::::::::::::::
/*
 * $Id: http-client.html,v 1.1 2009/06/22 16:12:13 kishi Exp kishi $ 
 */

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

#include "./common.h"

#define BUF_LEN 8192

int
main (int argc, char *argv[])
{
  int sock;
  char buf[BUF_LEN];
  char *hostname;

  if (argc != 2) {
    printf ("Usage: %s [hostname]\n", argv[0]);
    exit (1);
  }
  hostname = argv[1];

  sock = getConnection (hostname);

  sprintf (buf, "GET / HTTP/1.1\r\n");
  write (sock, buf, strlen (buf));

  sprintf (buf, "Host: %s\r\n", hostname);
  write (sock, buf, strlen (buf));

  sprintf (buf, "\r\n");
  write (sock, buf, strlen (buf));

  while (1) {
    int size;
    size = read (sock, buf, BUF_LEN);
    if (size > 0) {
      write (1, buf, size);
    }
    else {
      break;
    }
  }

  // fprintf (stderr, "--- closed ---\n");

  close (sock);

  return 0;
}
::::::::::::::
getConnection.c
::::::::::::::
/*
 * $Id: http-client.html,v 1.1 2009/06/22 16:12:13 kishi Exp kishi $
 */

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

#define PORT 80

int
getConnection (char *hostname)
{

  struct sockaddr_in addr;
  struct hostent *he;
  int sock;

  if ((sock = socket (AF_INET, SOCK_STREAM, 0)) < 0) {
    perror ("socket");
    exit (1);
  }

  bzero ((char *) &addr, sizeof (addr));

  if ((he = gethostbyname (hostname)) == NULL) {
    perror ("No such host");
    exit (1);
  }
  bcopy (he->h_addr, &addr.sin_addr, he->h_length);
  addr.sin_family = AF_INET;
  addr.sin_port = htons (PORT);

  if (connect (sock, (struct sockaddr *) &addr, sizeof (addr)) < 0) {
    perror ("connect");
    exit (2);
  }

  return sock;
}


戻る

inserted by FC2 system