2018年7月11日水曜日

開発環境

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

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

コード

Makefile

CC = cc

all: sample run

sample: sample.c
 $(CC) sample.c -o sample

run: sample
 ./sample
#include <arpa/inet.h>
#include <errno.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netdb.h>

void error(char *msg) {
  fprintf(stderr, "%s: %s\n", msg, strerror(errno));
  exit(1);
}

int open_socket(char *host, char *port) {
  struct addrinfo *res;
  struct addrinfo hints;
  memset(&hints, 0, sizeof(hints));
  hints.ai_family = PF_UNSPEC;
  hints.ai_socktype = SOCK_STREAM;
  if (getaddrinfo(host, port, &hints, &res) == -1) {
    error("アドレスを解決できません");
  }
  int d_sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
  if (d_sock == -1) {
    error("ソケットを開けません");
  }
  int c = connect(d_sock, res->ai_addr, res->ai_addrlen);
  freeaddrinfo(res);
  if (c == -1) {
    error("ソケットに接続できません");
  }
  return d_sock;
}

int say(int socket, char *s) {
  int result = send(socket, s, strlen(s), 0);
  if (result == -1) {
    fprintf(stderr, "サーバーとの通信エラー: %s\n", strerror(errno));
  }
  return result;
}

int main(int arc, char *argv[]) {
  int d_sock;

  /* d_sock = open_socket("en.wikipedia.org", "80"); */
  /* httpsなのでポート番号を変更 */
  d_sock = open_socket("en.wikipedia.org", "443");
  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 bytes_rcvd = recv(d_sock, rec, 255, 0);
  while (bytes_rcvd) {
    if (bytes_rcvd == -1) {
      error("サーバーから読み込めません");
    }
    rec[bytes_rcvd] = '\0';
    printf("%s", rec);
    bytes_rcvd = recv(d_sock, rec, 255, 0);
  }
  close(d_sock);
}

入出力結果(Terminal)

$ make
cc sample.c -o sample
./sample
<html>
<head><title>400 The plain HTTP request was sent to HTTPS port</title></head>
<body bgcolor="white">
<center><h1>400 Bad Request</h1></center>
<center>The plain HTTP request was sent to HTTPS port</center>
<hr><center>nginx/1.13.6</center>
</body>
</html>
$ ./sample python
<html>
<head><title>400 The plain HTTP request was sent to HTTPS port</title></head>
<body bgcolor="white">
<center><h1>400 Bad Request</h1></center>
<center>The plain HTTP request was sent to HTTPS port</center>
<hr><center>nginx/1.13.6</center>
</body>
</html>
$ 

0 コメント:

コメントを投稿