【问题标题】:How can I capture raw IP packets under Ubuntu?如何在 Ubuntu 下捕获原始 IP 数据包?
【发布时间】:2016-06-19 18:18:36
【问题描述】:

我想使用 Python 来捕获 Ubuntu 网络上的所有 IP 数据包。通过使用下面的代码,我得到了所有带有以太网头的数据包。如何去掉以太网报头,直接获取 IP 数据包?

s = socket.socket( socket.AF_PACKET , socket.SOCK_RAW , socket.ntohs(0x0003))
while True:
    packet = s.recvfrom(65565)

【问题讨论】:

  • Ethernet frame format 是众所周知的,如果您有 Ethernet frame,您可以轻松获取有效负载(即 IP 数据包)。
  • 谢谢。但是我的意思是有没有办法直接获取原始IP数据包,而不是在获取以太网数据包后进行其他处理?

标签: python linux ubuntu network-programming


【解决方案1】:

我建议您看看scapy,这是一个让用户能够发送、嗅探、剖析和伪造网络数据包的工具。 sniffing 段可能是您正在寻找的。这是一个示例,我捕获了 10 个 IP 数据包,显示了它们的信息摘要,然后将它们存储到 pcap 文件中:

$ scapy
Welcome to Scapy (2.3.2)
>>> pkts = sniff(filter='ip', count=10)
>>> print len(pkts)
10
>>> pkts.nsummary()
0000 Ether / IP / TCP 31.13.90.2:https > 192.168.1.14:63748 PA / Raw
0001 Ether / IP / TCP 192.168.1.14:63748 > 31.13.90.2:https A
0002 Ether / IP / TCP 192.168.1.14:63748 > 31.13.90.2:https PA / Raw
0003 Ether / IP / TCP 31.13.90.2:https > 192.168.1.14:63748 PA / Raw
0004 Ether / IP / TCP 192.168.1.14:63748 > 31.13.90.2:https A
0005 Ether / IP / UDP 192.168.1.21:48007 > 192.168.1.255:32412 / Raw
0006 Ether / IP / UDP 192.168.1.21:49808 > 192.168.1.255:32414 / Raw
0007 Ether / IP / UDP 192.168.1.11:64817 > 192.168.1.255:32412 / Raw
0008 Ether / IP / UDP 192.168.1.11:64819 > 192.168.1.255:32414 / Raw
0009 Ether / IP / UDP 192.168.1.11:49670 > 239.255.255.250:ssdp / Raw
>>> wrpcap("temp.cap",pkts)
>>> 

【讨论】:

    【解决方案2】:

    socket (AF_INET, SOCK_RAW, IPPROTO_RAW) 将为您提供 IP 层原始套接字

    socket (PF_PACKET, SOCK_RAW, htons (ETH_P_ALL)) 将为您提供第 2 层原始套接字`

    有例子(在 C 中)here

    【讨论】:

    • 这对我不起作用。也许它只适用于 C?
    • 原始套接字由操作系统提供关于语言的。两个 C 都应该进行完全相同的系统调用。您是否以提升的权限执行应用程序?
    • 我在我的程序中使用了同一行:s = socket.socket(socket.AF_PACKET,socket.SOCK_RAW,socket.ntohs(0x0003)) 并得到错误.. _sock = _realsocket(family, type, proto) socket.error: [Errno 1] Operation not allowed .. 我应该用什么来代替这些参数?
    • @ManishKumar 您需要 root 权限才能打开原始套接字。
    • @Malt 如果我使用 Django 框架,我该怎么做?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-05
    • 2012-06-17
    • 2012-08-20
    • 2013-10-29
    • 2010-09-07
    相关资源
    最近更新 更多