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.480)を解いてみる。
その他参考書籍
- プログラミング言語C 第2版 ANSI規格準拠 (B.W. カーニハン D.M. リッチー (著)、 石田 晴久 (翻訳)、共立出版)
- プログラミング言語Cアンサー・ブック 第2版 (クロビス・L.トンド、スコット・E.ギンペル(著)、矢吹 道郎(翻訳))
- C実践プログラミング 第3版 (Steve Oualline (著)、 望月 康司 (監訳) (翻訳)、 谷口 功 (翻訳)、 オライリージャパン)
長いエクササイズ(p.480)
コード(BBEdit, Emacs)
sample480.c
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <sys/socket.h>
#include <string.h>
#include "sample478.h"
#include "error.h"
#include "catch_signal.h"
int main(int argc, char *argv[])
{
if (catch_signal(SIGINT, handle_shutdown) == -1)
error("SIGINTハンドラを設定できません。");
listener_d = open_listener_socket();
bind_to_port(listener_d, 30000);
if (listen(listener_d, 10) == -1)
error("接続待ちできません。");
puts("接続を待っています。");
while (1) {
struct sockaddr_storage client_addr;
unsigned int address_size = sizeof(client_addr);
int connect_d = accept(listener_d, (struct sockaddr *) &client_addr,
&address_size);
if (say(connect_d, "Knock! Kncok!\r\n") != -1) {
char buf[100];
read_in(connect_d, buf, sizeof(buf));
if (strncmp(buf, "Who's there?", 12) == 0) {
if (say(connect_d, "Oscar\r\n") != -1) {
read_in(connect_d, buf, sizeof(buf));
if (strncmp(buf, "Oscar who?", 9) == 0)
say(connect_d, "oscar silly question, you get a silly answer\r\n");
}
}
}
close(connect_d);
}
return (0);
}
Makefile
CC=cc CFLAGS=-g -Wall SRC=sample478.c sample480.c error.c catch_signal.c OBJ=sample478.o sample480.o error.o catch_signal.o all: sample480 sample480: $(OBJ) $(CC) $(CFLAGS) $(OBJ) -o sample480 sample480.o: sample480.c $(CC) $(CFLAGS) -c sample480.c -o sample480.o sample478.o: sample478.c $(CC) $(CFLAGS) -c sample478.c -o sample478.o error.o: error.c $(CC) $(CFLAGS) -c error.c -o error.o catch_signal.o: catch_signal.c $(CC) $(CFLAGS) -c catch_signal.c -o catch_signal.o clear: rm -rf sample480 $(OBJ)
入出力結果(Terminal)
サーバー
$ make cc -g -Wall -c sample480.c -o sample480.o cc -g -Wall sample478.o sample480.o error.o catch_signal.o -o $ ./sample480 接続を待っています。 C-c C-cさようなら! $
クライアント
Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. Knock! Kncok! Who's there? Oscar Oscar who? oscar silly question, you get a silly answer Connection closed by foreign host. Process telnet-127.0.0.1 30000 exited abnormally with code 1
0 コメント:
コメントを投稿