用Wireshark簡單分析HTTP通信


我們都學過TCPHTTP的相關概念,本文借助協議分析工具Wireshark,讓大家對一些概念眼見為實,權當溫故而知新。

場景:

Client(10.239.196.211)上通過web browser訪問另一台Server(10.239.9.22)上的web server.

步驟:

0. 首先配置Wireshark -> Edit -> Preference -> Protocol:

如下配置的HTTP包顯示效果與TCP segment的時序比較一致,便於理解。

 

1. 用瀏覽器訪問 http://10.239.9.22:8080/同時打開Wireshark, 抓包如下:

2. 抓到的內容太多,先用Wireshark filter expression過濾一下: http

3. 然后我們找到了關心的packet, 右鍵 Follow -> TCP Stream找到所在的TCP Stream

於是得到了如下比較清爽的結果,呈現的即是"HTTP請求所用到的那個TCP connection"(在HTTP 1.1的實現中,同一個TCP Connection可以被多個HTTP通信復用。)

4. 一些分析

HTTP 層把下層的TCPPDU (也就是TCP segment)重新組裝成自己的PDU(也就是HTTP message)。在各個協議層,有不同的PDU,每個協議層要做2件事情:(i)把自己待發送的PDU交給下層去發送 (ii)把下層的收到PDU拿過來組裝成自己的PDU

TCP只負責發送自己的PDU,也就是TCP segmentTCP會把收到的數據放到自己的buffer里,那么何時這些數據會傳送給上層的HTTP呢?或者換句話說,HTTP如何知道該用哪些 TCP segment來拼成一個HTTP message呢?這就是PSH flag的作用。觀察下圖,我們會看到PSH flag總是出現在一個TCP傳輸最后一部分的HTTP message時。

關於PSH的權威解釋,可以看這個帖子:https://ask.wireshark.org/questions/20423/pshack-wireshark-capture

引用如下:

PSH is an indication by the sender that, if the receiving machine's TCP implementation has not yet provided the data it's received to the code that's reading the data (program, or library used by a program), it should do so at that point.  To quote RFC 793, the official specification for TCP:

The data that flows on a connection may be thought of as a stream of  octets.  The sending user indicates in each SEND call whether the data  in that call (and any preceeding calls) should be immediately pushed  through to the receiving user by the setting of the PUSH flag.

A sending TCP is allowed to collect data from the sending user and to  send that data in segments at its own convenience, until the push  function is signaled, then it must send all unsent data.  When a  receiving TCP sees the PUSH flag, it must not wait for more data from  the sending TCP before passing the data to the receiving process.

There is no necessary relationship between push functions and segment  boundaries.  The data in any particular segment may be the result of a  single SEND call, in whole or part, or of multiple SEND calls.

The purpose of push function and the PUSH flag is to push data through  from the sending user to the receiving user.  It does not provide a  record service.

我們實驗中的web server端的HTTP層就相當於引文中的sending user,實驗中的web browser端的HTTP層就相當於引文中的receving process

PSH flag的作用有2方面:

  • 對於發送方,就是把所有尚未發送的數據立刻發送出去
  • 對於接收方,就是不要再等未到達的數據,而把當前收到的數據全部交給上層協議。

以,web server所在機器的TCP協議在發送一個HTTP reponse時,當它意識到這是最后一個TCP segment時,就會加上PSH flag,然后所有buffer中尚未發送的數據都會被發送出去;而web browser所在機器的TCP協議在看到一個TCP segment帶有PSH flag時,就會意識到已經收到足夠信息了,應當立即把到目前為止已經收到的信息交給上層應用(即HTTP協議)。

簡單的說,PSH flag有點像我們寫文件時的flush操作。

 

還有幾點,稍微提一下:

  • TCP segment PDU)的數量不一定等於TCP ACK的數量
  • 數據的完整性和次序,通過SEQ/ACK number保證,ACK表示了"當前本方從對方已經收到的數據量"SEQ表示"當前本方已經向對方發送的數據量"。所以,如果通信得以順利完成,A方發給B方的ACK,最終應該等於B方最后一次的SEQ+LENGTH

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM