使用 Netcat 模擬 HTTP 請求

weixin_34146805發表於2018-11-28
3050552-07d3cbae82161dc8.png

Netcat 作為一款強大的網路工具,在開發及網路運維中可以發揮很大作用。本文說明一下使用 Netcat 進行 HTTP 除錯的方式。其實對於 HTTP,專業的工具很多,更好用,本文旨在以 HTTP 協議為例,演示 Netcat 作為基於 Socket 傳輸層 的工具,如何對於應用層協議的訪問進行除錯。

一、使用工具

二、基本使用說明

1、非互動式訪問

使用 GET 方法,訪問 http://httpbin.org/ip 獲取本機外網 IP

$ echo -e "GET /anything HTTP/1.0\r\nHost: httpbin.org\r\n\r\n" | nc httpbin.org 80

返回內容:

HTTP/1.1 200 OK
Connection: close
Server: gunicorn/19.9.0
Date: Wed, 28 Nov 2018 02:23:19 GMT
Content-Type: application/json
Content-Length: 248
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Via: 1.1 vegur

{
  "args": {},
  "data": "",
  "files": {},
  "form": {},
  "headers": {
    "Connection": "close",
    "Host": "httpbin.org"
  },
  "json": null,
  "method": "GET",
  "origin": "221.238.131.162",
  "url": "http://httpbin.org/anything"
}

說明:
這個例子,是通過 echo 命令,將 HTTP 的控制資訊通過通道,傳遞給 nc
(1)傳遞的資訊中,所有的回車換行,都以 \r\n 表示,對於最後一條控制語句,需要有兩個連續的 \r\n
(2)在指定協議版本的時候,可以指定為 HTTP/1.0HTTP/1.1

  • HTTP/1.0 訪問成功後,立即斷開連線,效果等同於加上 Connection: close
  • HTTP/1.1 訪問成功後,連線不會斷開,效果等同於加上 Connection: keep-alived,以保證連線可以複用,這種方式只有 HTTP 1.1 才支援。需要使用 Connection: close 控制命令斷開連線,或者 Ctrl + C 中止訪問。
2、互動式訪問
$ nc -c httpbin.org 80
GET /ip HTTP/1.0
Host: httpbin.org

返回內容:

HTTP/1.1 200 OK
Connection: close
Server: gunicorn/19.9.0
Date: Wed, 28 Nov 2018 02:36:52 GMT
Content-Type: application/json
Content-Length: 34
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Via: 1.1 vegur

{
  "origin": "221.238.131.162"
}

注意:
命令列中需要使用 -c 引數,以確保“回車換行”使用的是 \r\n

三、演示

1、GET 請求

http://httpbin.org/get 傳送 GET 請求,傳遞引數 a=1,b=2

$ nc -c httpbin.org 80
GET /get?a=1&b=2 HTTP/1.0
Host: httpbin.org

返回內容:

HTTP/1.1 200 OK
Connection: close
Server: gunicorn/19.9.0
Date: Wed, 28 Nov 2018 02:39:34 GMT
Content-Type: application/json
Content-Length: 199
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Via: 1.1 vegur

{
  "args": {
    "a": "1",
    "b": "2"
  },
  "headers": {
    "Connection": "close",
    "Host": "httpbin.org"
  },
  "origin": "221.238.131.162",
  "url": "http://httpbin.org/get?a=1&b=2"
}
2、POST 請求

http://httpbin.org/post 傳送 GET 請求,傳遞引數 a=1,b=2

$ nc -c httpbin.org 80
POST /post HTTP/1.0
Content-Type: application/x-www-form-urlencoded; charset=utf-8
Host: httpbin.org
Content-Length: 7

a=1&b=2

返回內容:

HTTP/1.1 200 OK
Connection: close
Server: gunicorn/19.9.0
Date: Wed, 28 Nov 2018 02:55:13 GMT
Content-Type: application/json
Content-Length: 356
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Via: 1.1 vegur

{
  "args": {},
  "data": "",
  "files": {},
  "form": {
    "a": "1",
    "b": "2"
  },
  "headers": {
    "Connection": "close",
    "Content-Length": "7",
    "Content-Type": "application/x-www-form-urlencoded; charset=utf-8",
    "Host": "httpbin.org"
  },
  "json": null,
  "origin": "221.238.131.162",
  "url": "http://httpbin.org/post"
}

(完)

相關文章