0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ncat でお手軽 HTTP サーバ

Posted at

固定値を返す HTTP サーバ

以下を実行すると 8080 ポートで待ち受けます。
アクセスすると固定値として "Hello" が返されます。

ncat -lkp 8080 -c 'printf "HTTP/1.0 200 OK\r\n\r\nHello"'

上記をロングオプションに置き換えた版とオプションの意味:

ncat --listen --keep-open --source-port 8080 --sh-exec 'printf "HTTP/1.0 200 OK\r\n\r\nHello"'
  • -l (--listen) - 接続を待ち受ける
  • -k (--keep-open) - 複数の接続を許可する
  • -p (--source-port) - 指定したポートで待ち受ける
  • -c (--sh-exec) - sh でコマンドを実行する

レスポンスを別スクリプトで生成する

レスポンスが長くなる場合は -c (--sh-exec) ではなく -e (--exec) オプションが便利です。

  • -c (--sh-exec) - sh でコマンドを実行する
  • -e (--exec) - sh 経由ではなくコマンドを直接実行する

例えば、レスポンスを生成する処理を response.sh に分離し、実行権限を付けておけば、次のように書くことができます。

ncat -lkp 8080 -e ./response.sh
response.sh (実行権限を付けておく)
#!/usr/bin/env bash

printf 'HTTP/1.0 200 OK\r\n\r\n'

cat <<EOS
<html>
    <head>
        <title>Hello</title>
    </head>
    <body>
        <h1>Hello</h1>
    </body>
</html>
EOS

リクエストヘッダを返す HTTP サーバ

標準入力を読み取り、最初の空行までを出力するスクリプトを書けば、リクエストヘッダを確認したいときに便利です。

ncat -lkp 8080 -e ./echo.sh
echo.sh (実行権限を付けておく)
#!/usr/bin/env bash

printf 'HTTP/1.0 200 OK\r\n\r\n'

while IFS="$(printf '\r\n')" read -r line
do
    if [ -z "${line}" ]; then
        break
    fi
    echo "${line}"
done
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?