6
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

IPv4ヘッダのチェックサム計算方法

Posted at

RFC読んだけどピンとこないのでとりあえずやってみた

データはこんな感じのバイナリ列
あるIPv4パケットを受信した時のデータ

0x45 0x00 0x16 0xce 0x65 0x4c 0x40 0x00 
0x01 0x11 0xf7 0xeb 0xc0 0xa8 0x65 0x1f 
0xe0 0x00 0x00 0x1f 

オプション無しの20BYTEが対象になる。
ここの0xf7 0xebがチェックサム。覚えておく。

2BYTEづつ計算していく

0x4500 + 0x16ce = 0x5bce
0x5bce + 0x654c = 0xc11a
0xc11a + 0x4000 = 0x1011a

桁が上がったら上がった分を1の位に加算して16bit化する
0x1011a → 0x011b

0x011b + 0x0111 = 0x022c
つぎは0xf7ebだけど、チェックサムなので飛ばして
0x022c + 0xc0a8 = 0xc2d4
0xc2d4 + 0x651f = 0x127f3
0x127f3 → 0x27f4
0x27f4 + 0xe000 = 0x107f4
0x107f4 → 0x07f5
0x07f5 + 0x001f = 0x0814

これでsumは終わり…
0x0814を反転させて
0xf7eb

おわり!OK!

補足

チェックサムが0の時はチェックサムを計算しなくていいみたい
正しいことが保証されるわけじゃないところが注意

補足2

上記の方法で計算したチェックサムは絶対0にはならんのだな
0xFFFFに1を足すと0x10000になるので結果としては0x0001
がチェックサムになるもんね。へぇー

6
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?