Impacket sniff.py
libpcap でパケットを取得し、リンク層の形式に応じてデコードして表示します。
| 項目 | 内容 |
|---|---|
| 実装 | examples/sniff.py |
| カテゴリ | パケット / ICMP / キャプチャ |
| 規模 | 112 行 |
| 配布 | setup.py の scripts=examples/*.py によりスクリプトとしてインストール |
CLI と入力
Section titled “CLI と入力”この古い形式のサンプルは -h を解釈しないため、usage とトップレベルの sys.argv 処理を確認します。
python examples/sniff.py [BPF filter ...]引数全体を空白で連結して pcapy.setfilter() へ渡します。無指定なら空の
filter、つまり全 packet が対象です。interface は引数ではなく、pcap から
取得した一覧を実行時に対話選択します。
詳細な処理フロー
Section titled “詳細な処理フロー”利用可能 interface を表示して選択し、pcapy.open_live() で capture handle を開きます。DecoderThread が packet callback を受け、pcap datalink type に対応する decoder で protocol tree を作って表示します。
仕組みの詳細
Section titled “仕組みの詳細”pcapy.open_live() は選択 interface の libpcap capture handle を作り、
snaplen 1500、non-promiscuous、短い read timeout で packet を受け取ります。
CLI の残り文字列は BPF expression として kernel/libpcap filter へ渡されるため、
filter 後の packet だけが Python callback に届きます。
capture byte 列の最初の header は interface の datalink type で変わります。
Ethernet なら EthDecoder、Linux cooked capture なら LinuxSLLDecoder を選び、
その decoder が Ether/SLL→IP→TCP 等の child hierarchy を構築します。
IP decoder を固定で使わないのは link-layer header の長さと形式が違うためです。
DecoderThread は pcap.loop(0, callback) で停止要求まで走り、各 packet を
人間可読表現として直ちに表示します。capture file 保存、flow reconstruction、
packet reassembly は行いません。未知 datalink type、callback 例外、interface
消失時に thread だけ黙って終了しないこと、明示的な停止/handle close を追加する
ことが保守上の改善点です。
主要な実装要素
Section titled “主要な実装要素”| シンボル | 位置 | 責務を追う入口 |
|---|---|---|
DecoderThread | 40 | __init__()、run()、packetHandler() |
getInterface() | 66 | モジュール関数 |
main() | 91 | モジュール関数 |
Impacket 内部
Section titled “Impacket 内部”| モジュール | 使用する主な名前 |
|---|---|
impacket | version |
impacket.ImpactDecoder | EthDecoder, LinuxSLLDecoder |
外部パッケージ(直接使用)
Section titled “外部パッケージ(直接使用)”| import 名 | 配布パッケージ | 経路・宣言状態 |
|---|---|---|
pcapy | pcapy | 直接 import、直接依存には未宣言 |
出力・副作用・必要権限
Section titled “出力・副作用・必要権限”- network probe または live packet capture を行います。送受信範囲、interface、filter と取得データの取扱いを確認してください。
- 待受 socket または長時間 loop を開始します。bind address、port、停止方法、同時接続時の共有状態を確認してください。
- raw socket または packet capture の権限が必要になる場合があります。取得データには第三者通信が含まれ得ます。
失敗経路と後始末
Section titled “失敗経路と後始末”- 停止要求、client 切断、partial read/write、worker 例外で listener 全体が不整合にならないことを確認します。
実装を変更するとき
Section titled “実装を変更するとき”pcapy、EthDecoder、LinuxSLLDecoder、threading に依存します。pcapy は project の直接依存に宣言されていません。capture 権限、snaplen、promiscuous mode、未知 link type の扱いを変更時に確認してください。
- 構文:
python -m py_compile examples/sniff.py - CLI: 引数なし/不足時の usage と終了 code を subprocess で確認する。
- このコマンド専用のテストは見つかりません。共有モジュールのテストと、必要に応じて隔離環境での動作確認を選びます。

