LoginSignup
9

More than 5 years have passed since last update.

シェルスクリプトでTCPの読み書きをする

Last updated at Posted at 2014-01-07

LinuxではシェルスクリプトだけでTCPの読み書きが出来るのでやり方をメモ。

BASHでTCPクライアント

#適当なファイルディスクリプタでTCPを開く(0,1,2は標準入力/出力/エラーで使われてるからそれ以外)
exec 5<>/dev/tcp/www.google.com/80

#先程のディスクリプタに対して書き込む
echo "GET / HTTP/1.1" >&5
echo "Host: www.google.com" >&5
echo >&5

#レスポンスをディスクリプタから読み込む
cat <&5
HTTP/1.1 302 Found
Location: http://www.google.co.jp/?gws_rd=cr&ei=5azLUvfcBczRkwXW4oCADw
Cache-Control: private
Content-Type: text/html; charset=UTF-8
Set-Cookie: PREF=ID=bcfe5bc4c98312a1:FF=0:TM=1389079781:LM=1389079781:S=syDn3Htc1dVCRLQ8; expires=Thu, 07-Jan-2016 07:29:41 GMT; path=/; domain=.google.com
Set-Cookie: NID=67=hRM9vKYySsBxDFxWTWC92D5ThwJy08b4A894fGt6ZyXIIhaWkbfB-vpdO44-jb6LJIO_dJnMVGaP_5QIus2HNqHNvSHc9tq84lLIBA6N-YWwKizdOpVIyPvqKDiPieX3; expires=Wed, 09-Jul-2014 07:29:41 GMT; path=/; domain=.google.com; HttpOnly
P3P: CP="This is not a P3P policy! See http://www.google.com/support/accounts/bin/answer.py?hl=en&answer=151657 for more info."
Date: Tue, 07 Jan 2014 07:29:41 GMT
Server: gws
Content-Length: 261
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN
Alternate-Protocol: 80:quic

<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>302 Moved</TITLE></HEAD><BODY>
<H1>302 Moved</H1>
The document has moved
<A HREF="http://www.google.co.jp/?gws_rd=cr&amp;ei=5azLUvfcBczRkwXW4oCADw">here</A>.
</BODY></HTML>

BASHでTCPサーバ

残念ながらBash単体ではTCPのbind(LISTEN)は出来ないのでTCPサーバにはなれません。他のコマンド使って下さい。

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
9