【发布时间】:2014-10-14 00:57:57
【问题描述】:
根据 python 文档,我们可以构建简单的嗅探器:
import socket
# the public network interface
HOST = socket.gethostbyname(socket.gethostname())
# create a raw socket and bind it to the public interface
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP)
s.bind((HOST, 0))
# Include IP headers
s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
# receive all packages
s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)
# receive a package
print s.recvfrom(65565)
# disabled promiscuous mode
s.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF)
适用于 windows 平台,但在 linux 中 socket.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF) 不起作用。
该示例将如何查找 linux 平台?如何在 Linux 中设置混杂模式?
编辑
我有一条消息:
Traceback (most recent call last):
File "b.py", line 46, in <module>
sniffer(count=10,showPort=True,showRawData=True)
File "b.py", line 12, in sniffer
s.bind((HOST, 0))
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 19] No such device
当我对@Christian-James-Bell 的代码做了一些更改时:
import socket
def sniffer(count, bufferSize=65565, showPort=False, showRawData=False):
# the public network interface
HOST = socket.gethostbyname(socket.gethostname())
# create a raw socket and bind it to the public interface
s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.IPPROTO_IP)
# prevent socket from being left in TIME_WAIT state, enabling reuse
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, 0))
# Include IP headers
s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
# receive all packages
s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)
for i in range(count):
# receive a package
package = s.recvfrom(bufferSize)
printPacket(package, showPort, showRawData)
# disabled promiscuous mode
s.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF)
def printPacket(package, showPort, showRawData):
# index values for (data, header) tuple
dataIndex = 0
headerIndex = 1
# index values for (ipAddress, port) tuple
ipAddressIndex = 0
portIndex = 1
print('IP:', package[headerIndex][ipAddressIndex])
if(showPort):
print('Port:', package[headerIndex][portIndex])
print ('') #newline
if(showRawData):
print ('Data:', package[dataIndex])
sniffer(count=10,showPort=True,showRawData=True)
有人知道怎么回事吗?
【问题讨论】:
-
关于您的更新:看起来操作系统不允许您访问。我认为您应该首先检查您是否处于管理员模式:检查 os.geteuid() == True。看这里:stackoverflow.com/questions/14950378/…