2014年9月28日日曜日

開発環境

Head First C ―頭とからだで覚えるCの基本(David Griffiths (著)、Dawn Griffiths (著) 中田 秀基(監訳)(翻訳)、木下 哲也 (翻訳)、オライリージャパン)の11章(ソケットとネットワーキング: 127.0.0.1という場所はない)、自分で考えてみよう(p.487)を解いてみる。

その他参考書籍

自分で考えてみよう(p.487)

コード(BBEdit, Emacs)

sample487.c

#include <stdio.h>
#include <stdlib.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 (!fork()) {
      close(listener_d);
      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);
      exit(0);
    }
    close(connect_d);
  }

  return (0);
}

Makefile

CC=cc
CFLAGS=-g -Wall
SRC=sample478.c sample487.c error.c catch_signal.c
OBJ=sample478.o sample487.o error.o catch_signal.o

all: sample487

sample487: $(OBJ)
 $(CC) $(CFLAGS) $(OBJ) -o sample487

sample487.o: sample487.c
 $(CC) $(CFLAGS) -c sample487.c -o sample487.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 sample487 $(OBJ)

入出力結果(Terminal)

サーバー

$ make && ./sample487
cc -g -Wall -c sample487.c -o sample487.o
cc -g -Wall sample478.o sample487.o error.o catch_signal.o -o sample487
接続を待っています。
  C-c C-cさようなら!
$

クライアント1

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

クライアント2

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<1> exited abnormally with code 1

0 コメント:

コメントを投稿