2014年4月25日金曜日

開発環境

Head First C ―頭とからだで覚えるCの基本(David Griffiths (著)、Dawn Griffiths (著) 中田 秀基(監訳)(翻訳)、木下 哲也 (翻訳)、オライリージャパン)の11章(ソケットとネットワーキング)、コードマグネット(p.494)を解いてみる。

その他参考書籍

コードマグネット(p.494)

コード(BBEdit, Emacs)

server_client.h

int read_in(int socket, char *buf, int len);
int open_listener_socket();
void bind_to_prot(int socket, int port);
int say(int socket, char *s);
void handle_shutdown(int sig);
int catch_signal(int sig, void (*handler)(int));
int listner_d;
int open_socket(char *host, char *port);

sample494.c

#include <stdio.h7gt;
#include <sys/socket.h7gt;
#include <unistd.h7gt;

#include "server_client.h"
#include "error.h"

int main(int argc, char *argv[])
{
  int d_sock;
  d_sock = open_socket("example.com", "80");
  char buf[255];

  /* httpを大文字にしないと、example.comには接続できなかった */
  /* 小文字のままで接続できるドメインもあったから、サーバー側の設定次第? */
  sprintf(buf, "GET /%s HTTP/1.1\r\n", argv[1]);
  say(d_sock, buf);

  say(d_sock, "Host: example.com\r\n\r\n");
  char rec[256];
  int bytesRcvd = recv(d_sock, rec, 255, 0);
  while (bytesRcvd) {
    if (bytesRcvd == -1)
      error("サーバーから読み込めません");
    rec[bytesRcvd] = '\0';
    printf("%s", rec);
    bytesRcvd = recv(d_sock, rec, 255, 0);
  }
  close(d_sock);

  return (0);
}

Makefile

all: sample494

sample494: sample494.c error.o server_client.o
 cc -g -o sample494 sample494.c error.o server_client.o

server_client.o: server_client.c error.o
 cc -c -o server_client.o server_client.c

error.o: error.c
 cc -c -o error.o error.c

clean:
 rm -rf sample494

入出力結果(Terminal)

$ ./sample494 index.html
HTTP/1.1 200 OK
Accept-Ranges: bytes
Cache-Control: max-age=604800
Content-Type: text/html
Date: Fri, 25 Apr 2014 08:19:12 GMT
Etag: "359670651"
Expires: Fri, 02 May 2014 08:19:12 GMT
Last-Modified: Fri, 09 Aug 2013 23:54:35 GMT
Server: ECS (sjc/169D)
X-Cache: HIT
x-ec-custom-error: 1
Content-Length: 1270

<!doctype html7gt;
<html>
省略...
</html>
$

0 コメント:

コメントを投稿