0230-TCP 傳送和接收

波尔發表於2024-08-14

環境

  • Time 2022-11-25
  • WSL-Ubuntu 22.04
  • Rust 1.65.0

前言

說明

參考:https://doc.rust-lang.org/std/net/struct.TcpListener.html

目標

之前認識了 TCP 報文頭,這裡去除報文頭的細節,直接通訊。

main.rs

TCP 由標準庫直接支援,可以直接使用。
連線上去後,伺服器返回一個 hello。

use std::{io::Write, net::TcpListener};

fn main() -> std::io::Result<()> {
    let listener = TcpListener::bind("127.0.0.1:4444")?;

    for stream in listener.incoming() {
        stream?.write_all("hello".as_bytes())?;
    }
    Ok(())
}

傳送請求

root@jiangbo12490:~# nc  127.0.0.1 4444
hello^C

TCPDUMP 抓包

oot@jiangbo12490:~# tcpdump -A -n -i lo port 4444
tcpdump: verbose output suppressed, use -v[v]... for full protocol decode
listening on lo, link-type EN10MB (Ethernet), snapshot length 262144 bytes



21:57:44.763832 IP 127.0.0.1.47456 > 127.0.0.1.4444: Flags [S], seq 4268043973, win 65495, options [mss 65495,sackOK,TS val 456644871 ecr 0,nop,wscale 7], length 0
E..<..@.@............`.\.e...........0.........
.7..........
21:57:44.763839 IP 127.0.0.1.4444 > 127.0.0.1.47456: Flags [S.], seq 2090178755, ack 4268043974, win 65483, options [mss 65495,sackOK,TS val 456644871 ecr 456644871,nop,wscale 7], length 0
E..<..@.@.<..........\.`|....e.......0.........
.7...7......
21:57:44.763845 IP 127.0.0.1.47456 > 127.0.0.1.4444: Flags [.], ack 1, win 512, options [nop,nop,TS val 456644871 ecr 456644871], length 0
E..4..@.@............`.\.e..|........(.....
.7...7..
21:57:44.763923 IP 127.0.0.1.4444 > 127.0.0.1.47456: Flags [P.], seq 1:6, ack 1, win 512, options [nop,nop,TS val 456644871 ecr 456644871], length 5
E..9.Z@.@..b.........\.`|....e.......-.....
.7...7..hello
21:57:44.763943 IP 127.0.0.1.47456 > 127.0.0.1.4444: Flags [.], ack 6, win 512, options [nop,nop,TS val 456644871 ecr 456644871], length 0
E..4. @.@............`.\.e..|........(.....
.7...7..
21:57:44.763951 IP 127.0.0.1.4444 > 127.0.0.1.47456: Flags [F.], seq 6, ack 1, win 512, options [nop,nop,TS val 456644871 ecr 456644871], length 0
E..4.[@.@..f.........\.`|....e.......(.....
.7...7..
21:57:44.806605 IP 127.0.0.1.47456 > 127.0.0.1.4444: Flags [.], ack 7, win 512, options [nop,nop,TS val 456644913 ecr 456644871], length 0
E..4.!@.@............`.\.e..|........(.....
.7.1.7..
21:57:50.407455 IP 127.0.0.1.47456 > 127.0.0.1.4444: Flags [F.], seq 1, ack 7, win 512, options [nop,nop,TS val 456650514 ecr 456644871], length 0
E..4."@.@............`.\.e..|........(.....
.7...7..
21:57:50.407475 IP 127.0.0.1.4444 > 127.0.0.1.47456: Flags [.], ack 2, win 512, options [nop,nop,TS val 456650514 ecr 456650514], length 0
E..4..@.@.<..........\.`|....e......T......
.7...7..

一共 9 次報文交換,三次握手,一次資料傳送,一次資料確認,四次揮手。

總結

使用 Rust 的標準庫,實現 TCP 的通訊。

附錄

相關文章