问题
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)
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.
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.
Where I'm going wrong with this?
回答1:
On 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))
Need to open RAW not TCP.
Edit for comment :
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" mean :
0800 = IP4 = IP version (IPv4)5 = Header length (5 words of 4 bytes each)
来源:https://stackoverflow.com/questions/38300753/python-tcp-raw-socket-not-listening-on-lo-localhost-127-0-0-1