【问题标题】:How to extract an IPv4 address from a Packet? [closed]如何从数据包中提取 IPv4 地址? [关闭]
【发布时间】:2014-03-29 22:57:46
【问题描述】:

我有这个byte[] 代表IPv4 packet

byte[] arr = { 0, 48, 136, 21, 69, 131, 0, 24, 231, 253, 174, 161, 8, 0, 69, 0, 0, 52, 2, 31, 64, 0, 128, 6, 230, 22, 212, 25, 99, 74, 202, 177, 16, 121, 194, 156, 0, 119, 160, 128, 75, 200, 249, 141, 210, 78, 80, 24, 64, 252, 130, 182, 0, 0, 65, 82, 84, 73, 67, 76, 69, 32, 51, 52, 13, 10 };

我想计算IPV4 address

【问题讨论】:

  • 看看这里,这对你有帮助吗? en.wikipedia.org/wiki/IPv4#Header
  • 你想要哪个IPv4 address
  • 我展示了但不明白这个以及如何计算我的IP地址
  • 首先,在我看来,这不像是 IP 数据包
  • 我要源和目的

标签: c# ip packet


【解决方案1】:

这里有一个简单的解析器来检查你的字节数组:

void Main()
{
    byte[] arr = { 0, 48, 136, 21, 69, 131, 0, 24, 231, 253, 174, 161, 8, 0, 69, 0, 0, 52, 2, 31, 64, 0, 128, 6, 230, 22, 212, 25, 99, 74, 202, 177, 16, 121, 194, 156, 0, 119, 160, 128, 75, 200, 249, 141, 210, 78, 80, 24, 64, 252, 130, 182, 0, 0, 65, 82, 84, 73, 67, 76, 69, 32, 51, 52, 13, 10 };
    var stream = new MemoryStream(arr, 0, arr.Length);
    var reader = new BinaryReader(stream);

    Print("Version and header length", reader.ReadByte());
    Print("Diff services", reader.ReadByte());

    Print("Total length", IPAddress.NetworkToHostOrder(reader.ReadInt16())); 
    Print("ID", IPAddress.NetworkToHostOrder(reader.ReadInt16()));
    Print("Flags and offset", IPAddress.NetworkToHostOrder(reader.ReadInt16()));

    Print("TTL", reader.ReadByte());
    Print("Protocol", reader.ReadByte());
    Print("Checksum", reader.ReadInt16());

    Print("Source IP", new IPAddress((int) reader.ReadInt32()));
    Print("Destination IP", new IPAddress((int) reader.ReadInt32()));
}

这会产生这个输出:

Version and header length = 0
Diff services = 48
Total length = -30699
ID = 17795
Flags and offset = 24
TTL = 231
Protocol = 253
Checksum = -24146
Source IP = 8.0.69.0
Destination IP = 0.52.2.31

这似乎不太正确(负长度/校验和?+ 协议应为 TCP 返回“6”或为 UDP 返回“8”)。您可能需要先验证您的数据是否正确。

我使用来自a tiny project of mine 的代码编写了这个代码,这可能会帮助您解决未来的问题。一定要看看wikipedia 上的数据包布局,DNS/UDP 也需要它。

【讨论】:

  • 这个项目在做什么?
  • @user3271698:它是一个小型的、有缺陷的数据包嗅探器。它从传出数据包中读取 IP、TCP/UDP 和 DNS/HTTP 标头(传入数据包不多,请参阅here)。
  • 是否可以用 IPv6 地址替换 IPv4 地址?
  • 您可以在标头的前 4 位查看 IP 版本,包括 IPv4 和 IPv6,如您所见 here。读取前 4 位并根据该结果执行额外的解析。真的,只需在您的信息流中调用readX() 即可。
  • 我可以有代码示例吗? (我是新开发者...)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-25
  • 1970-01-01
  • 2010-11-06
  • 1970-01-01
  • 1970-01-01
  • 2010-11-19
  • 1970-01-01
相关资源
最近更新 更多