【问题标题】:Parsing UDP header within IP header VB.NET在IP头VB.NET中解析UDP头
【发布时间】:2017-12-06 00:18:43
【问题描述】:

我正在做一个网络嗅探器。我在我的主网络接口(192.168.2.11)上打开了一个原始套接字监听。该代码并不是真正需要的,但如果您需要,我可以提供。然后,我从收到的数据包中创建一个MemoryStream(它应该包含一个 IP 标头,后跟一个 UDP 标头,最后是一个数据报)。我把这个MemoryStream转换成BinaryReader,然后用下面的流程解析IP头

Version and header length        BinaryReader.ReadByte() 'As two nibbles make a byte
Type of service                  BinaryReader.ReadByte()
Total length                     BinaryReader.ReadInt16()
Identification                   BinaryReader.ReadInt16()
Flags and offset                 BinaryReader.ReadInt16() 'As 3 bits + 13 bits is 16
Time to live                     BinaryReader.ReadByte()
Protocol                         BinaryReader.ReadByte()
Checksum                         BinaryReader.ReadInt16()
Source address                   BinaryReader.ReadInt32()
Destination address              BinaryReader.ReadInt32()

(对此数据进行了更多处理,但未对BinaryReader进行任何更改)

然后查询Version字段是否为17(UDP),如果是则继续下一步,否则丢弃该过程。

现在我检查 Internet 标头长度 (IHL) 是否为 5(即 5 * 32 或 160 位,或 20 字节)。我这样做是为了确保我的程序不会因不必要的 IP 选项而跳闸。如果不是5,我就放弃这个过程。

IP 标头解析完美...现在使用完全相同的BinaryReader,我尝试解析封装的 UDP 标头。我为此使用的代码是

Out("Source port?: " & IPAddress.NetworkToHostOrder(bin.ReadInt16()))
Out("Destination port?: " & IPAddress.NetworkToHostOrder(bin.ReadInt16()))
Out("Length?: " & IPAddress.NetworkToHostOrder(bin.ReadInt16()))
Out("Checksum?: " & IPAddress.NetworkToHostOrder(bin.ReadInt16()))

但我总是得到一些荒谬的东西......这是我的控制台应用程序的输出

Source port?: -364
Destination port?: 53
Length?: 35
Checksum?: -7570

Destination 看起来不错,DNS 为 53,那么 length 看起来也不错,但源?端口怎么可能是负数?并且校验和可能被允许为负,我不确定。我的代码有什么问题?如果你需要IP头输出,就在这里...

Version: 4 (0100)
Internet header length: 5
    Words (32 bits): 5
    Octets (8 bits): 20
    Bits (1 bit): 160
Type of service: 0x00000000
    Precedence: 000 (Routine)
    Delay: 0 (Normal Delay)
    Throughput: 0 (Normal Throughput)
    Reliability: 0 (Normal Reliability)
Total length: 55
Identification: 2866
Flags: 0x00
    Reserved: False
    Don't Fragment: False
    More Fragments: False
Fragment offset: 0
Time to live: 128
Protocol: 17 (UDP)
Header checksum: -21977
Source address: 184723648 (192.168.2.11)
Destination address: 16951488 (192.168.2.1)
Payload length (bits): 288

【问题讨论】:

  • UDP port numbers go from 0 to 65535 所以你需要一个 UInt16,而不是 Int16。
  • "然后查询Version字段是否为17(UDP),如果是则继续下一步,否则丢弃该过程。 “ 这是没有意义的。 Version 字段是 IP 版本,它应该是 46Protocol 字段应该是 17
  • @RonMaupin 我的错,在代码中我确实查询了协议,但我不小心输入了版本。
  • @AndrewMorton 太好了,我将其更改为 UInt16,谢谢 :)
  • @AndrewMorton 嗯,当我应该得到 5516 时,似乎 ReadUInt16 给了我 361496576...我正在使用 IPAddress.NetworkToHostOrder,你知道为什么会发生这种情况吗?

标签: vb.net sockets networking udp ip


【解决方案1】:

似乎问题不是我的解析方法(我知道),而是原始套接字返回的数据。当我使用 Wireshark 提供的十六进制转储时,效果很好。

【讨论】:

    猜你喜欢
    • 2015-11-02
    • 1970-01-01
    • 1970-01-01
    • 2012-01-13
    • 2011-01-27
    • 1970-01-01
    • 2011-01-13
    • 2014-02-08
    • 2010-11-08
    相关资源
    最近更新 更多