kangkang's blog

标题: 使用nc的httpd
2009-08-31 14:54:46

netcat是网络工具中的瑞士军刀,除了常规的网络检测探测,传送文件等,发挥想像,可以做多种与网络相关的事情。 下面是一个使用bash和nc写的httpd,因为nc不支持fork和SO_REUSEADDR这类的特性,只支持一个连接。

用法: ./httpd.sh filename # filename是一个想用来传输的文件 客户端可用各种浏览器打开 http://IP:8080/

#!/bin/bash
# Licence: GPLv3 http://www.gnu.org/licenses/gpl-3.0.txt
# Author: kangkang <kangkang0517 at gmail.com> 2009
#
# Filename: httpd.sh
#   A simple httpd with bash and nc(netcat).
#

filename=$1
length=$(wc -c "$filename"|awk '{print $1}')
mkfifo w 2>/dev/null
while :; do
 nc -l -p 8080 < w > r & pid=$!
 while :; do
   n=$(cat r|grep -n "^\s*$"|cut -f 1 -d ":")
   if [ -n "$n" ];then
     header="$(sed -n 1,${n}p r)"
     echo "$header" >> log
     echo -e "HTTP/1.1 200 OK"
     #echo "Content-Type: text/plain"
     echo "Content-Type: application/octet-stream"
     #echo "Accept-Range: bytes"
     echo "Content-Length: $length"
     echo ""
     cat $filename
     break
   fi
 done > w
 kill $!
done
发表于: Bash