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 (コンパイラ)
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 "open_socket.h"
#include "say.h"
#include "error.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("サーバーから読み込めません。", -1);
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 open_socket.c say.c error.c OBJ=sample494.o open_socket.o say.o error.o all: sample494 sample494: $(OBJ) $(CC) $(CFLAGS) $(OBJ) -o sample494 sample494.o: open_socket.h say.h error.h sample494.c $(CC) $(CFLAGS) -c sample494.c -o sample494.o open_socket.o: error.h 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 error.o: error.c $(CC) $(CFLAGS) -c error.c -o error.o clean: rm -rf sample494 $(OBJ)
入出力結果(Terminal)
$ ./sample494 "O'Reilly_Media" | less WARNING: terminal is not fully functional - (press RETURN) HTTP/1.1 200 OK Server: Apache X-Content-Type-Options: nosniff Content-language: en X-UA-Compatible: IE=Edge Vary: Accept-Encoding,Cookie Expires: Thu, 01 Jan 1970 00:00:00 GMT Last-Modified: Sat, 14 Jun 2014 02:46:22 GMT Content-Type: text/html; charset=UTF-8 X-Varnish: 352469796, 1122069883, 3178356805 Via: 1.1 varnish, 1.1 varnish, 1.1 varnish Content-Length: 58300 Accept-Ranges: bytes Date: Sun, 15 Jun 2014 04:55:27 GMT Age: 0 Connection: keep-alive X-Cache: cp1055 miss (0), cp4018 miss (0), cp4009 frontend miss (0) Cache-Control: private, s-maxage=0, max-age=0, must-revalidate Set-Cookie: GeoIP=JP::35.6900:139.6900:v4; Path=/; Domain=.wikipedia.org <!DOCTYPE html> <html lang="en" dir="ltr" class="client-nojs"> <head> :q $
0 コメント:
コメントを投稿