Head First C ―頭とからだで覚えるCの基本
(オライリージャパン)
David Griffiths (著) Dawn Griffiths (著)
中田 秀基(監訳)(翻訳) 木下 哲也 (翻訳)
開発環境
- OS X Mavericks - Apple、たまにFreeBSD 10(OS)
- Emacs (CUI)、BBEdit - Bare Bones Software, Inc. (GUI) (Text Editor)
- C (プログラミング言語)
- Clang/LLVM (コンパイラ)
Head First C ―頭とからだで覚えるCの基本(David Griffiths (著)、Dawn Griffiths (著) 中田 秀基(監訳)(翻訳)、木下 哲也 (翻訳)、オライリージャパン)の11章(ソケットとネットワーキング: 127.0.0.1という場所はない)、コードマグネット(p.494)を解いてみる。
その他参考書籍
- プログラミング言語C 第2版 ANSI規格準拠 (B.W. カーニハン D.M. リッチー (著)、 石田 晴久 (翻訳)、共立出版)
- プログラミング言語Cアンサー・ブック 第2版 (クロビス・L.トンド、スコット・E.ギンペル(著)、矢吹 道郎(翻訳))
- C実践プログラミング 第3版 (Steve Oualline (著)、 望月 康司 (監訳) (翻訳)、 谷口 功 (翻訳)、 オライリージャパン)
コードマグネット(p.494)
コード(BBEdit, Emacs)
sample494.c
#include <stdio.h> #include <unistd.h> #include <sys/socket.h> #include "error.h" #include "open_socket.h" #include "say.h" int main(int argc, char *argv[]) { int d_sock; d_sock = open_socket("en.wikipedia.org", "80"); char buf[255]; sprintf(buf, "GET /wiki/%s http/1.1\r\n", argv[1]); say(d_sock, buf); say(d_sock, "Host: en.wikipedia.org\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
CC=cc CFLAGS=-g -Wall SRC=sample494.c error.c open_socket.c say.c OBJ=sample494.o error.o open_socket.o say.o all: sample494 sample494: $(OBJ) $(CC) $(CFLAGS) $(OBJ) -o sample494 sample494.o: sample494.c $(CC) $(CFLAGS) -c sample494.c -o sample494.o error.o: error.c $(CC) $(CFLAGS) -c error.c -o error.o open_socket.o: open_socket.c $(CC) $(CFLAGS) -c open_socket.c -o open_socket.o say.o: say.c $(CC) $(CFLAGS) -c say.c -o say.o clear: rm -rf sample494 $(OBJ)
入出力結果(Terminal)
$ make cc -g -Wall -c sample494.c -o sample494.o cc -g -Wall sample494.o error.o open_socket.o say.o -o sample494 $ ./sample494 "O'Reilly_Media" HTTP/1.1 200 OK Server: Apache X-Content-Type-Options: nosniff Content-language: en X-UA-Compatible: IE=Edge Expires: Thu, 01 Jan 1970 00:00:00 GMT Last-Modified: Sat, 27 Sep 2014 12:49:10 GMT Content-Type: text/html; charset=UTF-8 Vary: Accept-Encoding,Cookie,X-Use-HHVM X-Varnish: 2230640981, 2815371771, 2395602133 Via: 1.1 varnish, 1.1 varnish, 1.1 varnish Content-Length: 60911 Accept-Ranges: bytes Date: Mon, 29 Sep 2014 03:12:04 GMT Age: 0 Connection: keep-alive X-Cache: cp1055 miss (0), cp4018 miss (0), cp4008 frontend miss (0) Cache-Control: private, s-maxage=0, max-age=0, must-revalidate X-Analytics: php=zend // 省略 </body> </html> $
0 コメント:
コメントを投稿