用dpkt解析ip地址

时间:2014-08-18 18:43:58

标签: python parsing pcap

我正在使用dpkt来解析pcap文件,但我对如何提取目标IP地址感到困惑。我使用eth = dpkt.ethernet.Ethernet(buf)解析数据包,它返回一个如下所示的以​​太网对象:

Ethernet(src='\x00\x1a\xa0kUf', dst='\x00\x13I\xae\x84,', data=IP(src='\xc0\xa8\n\n',
off=16384, dst='C\x17\x030', sum=25129, len=52, p=6, id=51105, data=TCP(seq=9632694,
off_x2=128, ack=3382015884, win=54, sum=65372, flags=17, dport=80, sport=56145)))

我对两件事感到困惑。

  1. 我应该抓住以太网中的dst字段,还是IP(Ethernet.data)中的dst字段?
  2. 如何将这些奇怪的字符串转换为x.x.x.x格式的ip地址,其中x是0-255之间的整数?
  3. 我尝试了像Convert "little endian" hex string to IP address in Python这样的解决方案,但两个dst字段似乎有时包含似乎无法解析为_daQ的IP地址的数据(如何解析_daQ以解决?)或{ {1}}(什么是RT?)或RT\x00\x125\x02(开头的33是什么,为什么这看起来像5个字节而不是4?)

1 个答案:

答案 0 :(得分:7)

  1. eth.dst字段将包含目标MAC地址(例如01:23:45:67:89:ab),而不是目标IP地址。你需要ip.dst字段。
  2. 字符串是字节字符串,而不是ASCII(或其他)编码的可读字符串。
  3. 试试这个:

    ip_hdr = eth.data
    ip_hdr.dst  # will contain your destination IP address in BINARY
    
    # adapted from http://www.commercialventvac.com/dpkt.html#mozTocId303989
    import socket
    dst_ip_addr_str = socket.inet_ntoa(ip_hdr.dst)