Python TCP原始套接字未在lo上侦听(localhost/127.0.0.1) [英] Python TCP raw socket not listening on lo (localhost/ 127.0.0.1)
问题描述
我使用Python中的原始套接字创建了一个简单的数据包嗅探器.
I created a simple packet sniffer using raw socket in Python.
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_TCP)
while True:
print s.recvfrom(1600)
正在显示的互联网流量.但是,当我关闭主网络接口并通过lo
接口(源和目标127.0.0.1)使用scapy发送syn数据包时,什么也没打印.
The internet traffic it's showing. But when I turn the primary network interface down and send syn packets using scapy through the lo
interface (source and destination 127.0.0.1), There's nothing printed.
基本上,我使用scapy创建和发送10个syn数据包,其源和目标是127.0.0.1,这在Wireshark中可见.但是这不是嗅探器.我认为可能存在长度问题.因此,我将缓冲区大小设置为syn数据包的大小,即74(s.recvfrom(74)
),但还是没有.一旦我再次打开主网络接口,它就会显示所有TCP通信.
Basically I create and send 10 syn packets using scapy whose source and destination is 127.0.0.1, which is visible in wireshark. But not in this sniffer. I thought there might be a problem of the length. So I set the buffer size to a syn packet's size i.e. 74 (s.recvfrom(74)
), but still nothing. As soon as I turn the primary network interface up again, it shows all the TCP traffic.
我需要关闭网络接口,以免收到我自己创建的流量之外的其他流量.
I need to turn off the network interface so that I won't receive any other traffic other than my own created one.
我在哪里出错了?
推荐答案
在Linux上:
soc = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(3))
soc.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 2**30)
soc.bind(("eth0",0x0003))
需要打开RAW
而不是TCP
.
编辑评论:
a = soc.recvform(65565)[0]
h = binascii.hexlify(a)
if h[24:30] == "080045" and h[46:48] == "06":
# h[24:30] == "080045" Means IP (Type field of Ethernet Header
# combined with IP Version and IP header length)
# h[46:48] == "06" Means TCP (Ip Protocol field of IP Header)
#do something with TCP packet
"080045"的意思是:
0800
= IP
4
= IP版本(IPv4)
5
=标头长度(5个字,每个4个字节)
0800
= IP
4
= IP version (IPv4)
5
= Header length (5 words of 4 bytes each)
这篇关于Python TCP原始套接字未在lo上侦听(localhost/127.0.0.1)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!